Permalink
Browse files

Don't save has_one associations unnecessarily. Closes #5735.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4690 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent a27ccf1 commit 35670bbde59de9d0838027bd4fcd4cc04f928e3d @jeremy jeremy committed Aug 6, 2006
View
2 activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney]
+
* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson]
* Formally deprecate the deprecated finders. [Koz]
View
2 activerecord/lib/active_record/associations.rb
@@ -584,7 +584,7 @@ def has_one(association_id, options = {})
module_eval do
after_save <<-EOF
association = instance_variable_get("@#{reflection.name}")
- unless association.nil?
+ if !association.nil? && (new_record? || association.new_record? || association["#{reflection.primary_key_name}"] != id)
association["#{reflection.primary_key_name}"] = id
association.save(true)
end
View
17 activerecord/test/associations_test.rb
@@ -291,6 +291,23 @@ def test_assignment_before_either_saved
assert_equal a, firm.account
assert_equal a, firm.account(true)
end
+
+ def test_not_resaved_when_unchanged
+ firm = Firm.find(:first, :include => :account)
+ assert_queries(1) { firm.save! }
+
+ firm = Firm.find(:first)
+ firm.account = Account.find(:first)
+ assert_queries(1) { firm.save! }
+
+ firm = Firm.find(:first).clone
+ firm.account = Account.find(:first)
+ assert_queries(2) { firm.save! }
+
+ firm = Firm.find(:first).clone
+ firm.account = Account.find(:first).clone
+ assert_queries(2) { firm.save! }
+ end
end

0 comments on commit 35670bb

Please sign in to comment.