Skip to content

Commit

Permalink
Only call save on belongs_to associations if the record has changed o…
Browse files Browse the repository at this point in the history
…r any nested associations have changed (resolves rails#3353)
  • Loading branch information
chielwester committed Dec 13, 2010
1 parent 32a2bf8 commit 80fd46c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/autosave_association.rb
Expand Up @@ -363,7 +363,7 @@ def save_belongs_to_association(reflection)
if autosave && association.marked_for_destruction?
association.destroy
elsif autosave != false
saved = association.save(:validate => !autosave) if association.new_record? || autosave
saved = association.save(:validate => !autosave) if association.new_record? || (autosave && association.changed_for_autosave?)

if association.updated?
association_id = association.send(reflection.options[:primary_key] || :id)
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/autosave_association_test.rb
Expand Up @@ -667,10 +667,21 @@ def save(*args)
end
end

@ship.pirate.catchphrase = "Changed Catchphrase"

assert_raise(RuntimeError) { assert !@ship.save }
assert_not_nil @ship.reload.pirate
end

def test_should_save_changed_child_objects_if_parent_is_saved
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@parrot = @pirate.parrots.create!(:name => 'Posideons Killer')
@parrot.name = "NewName"
@ship.save

assert_equal 'NewName', @parrot.reload.name
end

# has_many & has_and_belongs_to
%w{ parrots birds }.each do |association_name|
define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do
Expand Down

0 comments on commit 80fd46c

Please sign in to comment.