Permalink
Browse files

Added test case and fix for proper eager loading associations

  • Loading branch information...
1 parent c1720fb commit 3836dc6b4ed5a2bda980871c31270e2195713a66 @fxposter fxposter committed with tenderlove Feb 27, 2011
@@ -85,7 +85,7 @@ module ClassMethods
# only one level deep in the +associations+ argument, i.e. it's not passed
# to the child associations when +associations+ is a Hash.
def preload_associations(records, associations, preload_options={})
- records = Array.wrap(records).compact.uniq
+ records = Array.wrap(records).compact
return if records.empty?
case associations
when Array then associations.each {|association| preload_associations(records, association, preload_options)}
@@ -97,6 +97,7 @@ def preload_associations(records, associations, preload_options={})
reflection = reflections[parent]
parents = records.sum { |record| Array.wrap(record.send(reflection.name)) }
unless parents.empty?
+ parents = parents.uniq if reflection.macro == :belongs_to
parents.first.class.preload_associations(parents, child)
end
end
@@ -156,6 +156,16 @@ def test_including_duplicate_objects_from_has_many
assert_equal [comment], category.posts[0].comments
end
end
+
+ def test_associations_loaded_for_all_records
+ post = Post.create!(:title => 'foo', :body => "I like cars!")
+ comment = SpecialComment.create!(:body => 'Come on!', :post => post)
+ first_category = Category.create! :name => 'First!', :posts => [post]
+ second_category = Category.create! :name => 'Second!', :posts => [post]
+
+ categories = Category.where(:id => [first_category.id, second_category.id]).includes(:posts => :special_comments)
+ assert_equal categories.map { |category| category.posts.first.special_comments.loaded? }, [true, true]
+ end
def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once
author_id = authors(:david).id

0 comments on commit 3836dc6

Please sign in to comment.