Skip to content

Fixing Identity Map when using find select #5647

Merged
merged 4 commits into from Mar 29, 2012
View
21 activerecord/lib/active_record/base.rb
@@ -954,23 +954,30 @@ def instantiate(record)
record_id = sti_class.primary_key && record[sti_class.primary_key]
if ActiveRecord::IdentityMap.enabled? && record_id
+ instance = use_identity_map(sti_class, record_id, record)
+ else
+ instance = sti_class.allocate.init_with('attributes' => record)
+ end
+
+ instance
+ end
+
+ private
+
+ def use_identity_map(sti_class, record_id, record)
if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
record_id = record_id.to_i
end
+
if instance = IdentityMap.get(sti_class, record_id)
instance.reinit_with('attributes' => record)
else
instance = sti_class.allocate.init_with('attributes' => record)
IdentityMap.add(instance)
end
- else
- instance = sti_class.allocate.init_with('attributes' => record)
- end
- instance
- end
-
- private
+ instance
+ end
def relation #:nodoc:
@relation ||= Relation.new(self, arel_table)
View
8 activerecord/lib/active_record/identity_map.rb
@@ -90,7 +90,7 @@ def get(klass, primary_key)
end
def add(record)
- repository[record.class.symbolized_sti_name][record.id] = record
+ repository[record.class.symbolized_sti_name][record.id] = record if contain_all_columns?(record)
end
def remove(record)
@@ -104,6 +104,12 @@ def remove_by_id(symbolized_sti_name, id)
def clear
repository.clear
end
+
+ private
+
+ def contain_all_columns?(record)
+ (record.class.column_names - record.attribute_names).empty?
+ end
end
# Reinitialize an Identity Map model object from +coder+.
View
17 activerecord/test/cases/identity_map_test.rb
@@ -404,18 +404,13 @@ def test_find_using_identity_map_respects_readonly
assert comment.save
end
- def test_find_using_select_and_identity_map
- author_id, author = Author.select('id').order(:id).first, Author.order(:id).first
+ def test_do_not_add_to_repository_if_record_does_not_contain_all_columns
+ author = Author.select(:id).first
+ post = author.posts.first
- assert_equal author_id, author
- assert_same author_id, author
- assert_not_nil author.name
-
- post, post_id = Post.order(:id).first, Post.select('id').order(:id).first
-
- assert_equal post_id, post
- assert_same post_id, post
- assert_not_nil post.title
+ assert_nothing_raised do
+ assert_not_nil post.author.name
+ end
end
# Currently AR is not allowing changing primary key (see Persistence#update)
Something went wrong with that request. Please try again.