Skip to content
Browse files

Cache nil results for :included has_one associations also. Closes #5787.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4783 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 4584376 commit 18057d2fb6017df988fadc6496f187c2e6208277 @jeremy jeremy committed Aug 17, 2006
View
4 activerecord/CHANGELOG
@@ -1,6 +1,8 @@
*SVN*
-* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Luetke]
+* Cache nil results for :included has_one associations also. #5787 [Michael Schoen]
+
+* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Luetke]
* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper]
Example: Invoice::Lineitem is given table name invoice_lineitems
View
10 activerecord/lib/active_record/associations.rb
@@ -870,7 +870,7 @@ def association_accessor_methods(reflection, association_proxy_class)
end
define_method("set_#{reflection.name}_target") do |target|
- return if target.nil?
+ return if target.nil? and association_proxy_class == BelongsToAssociation
association = association_proxy_class.new(self, reflection)
association.target = target
instance_variable_set("@#{reflection.name}", association)
@@ -1311,11 +1311,15 @@ def construct_association(record, join, row)
when :has_many, :has_and_belongs_to_many
collection = record.send(join.reflection.name)
collection.loaded
-
+
return nil if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
association = join.instantiate(row)
collection.target.push(association) unless collection.target.include?(association)
- when :has_one, :belongs_to
+ when :has_one
+ return if record.id.to_s != join.parent.record_id(row).to_s
+ association = join.instantiate(row) unless row[join.aliased_primary_key].nil?
+ record.send("set_#{join.reflection.name}_target", association)
+ when :belongs_to
return if record.id.to_s != join.parent.record_id(row).to_s or row[join.aliased_primary_key].nil?
association = join.instantiate(row)
record.send("set_#{join.reflection.name}_target", association)
View
3 activerecord/test/associations_test.rb
@@ -99,6 +99,9 @@ def test_has_one
def test_has_one_cache_nils
assert_nil companies(:another_firm).account
assert_queries(0) { companies(:another_firm).account }
+
+ firms = Firm.find(:all, :include => :account)
+ assert_queries(0) { firms.each(&:account) }
end
def test_proxy_assignment

0 comments on commit 18057d2

Please sign in to comment.
Something went wrong with that request. Please try again.