From 33c0454676e36167af17a49696fbaac5c283cfc8 Mon Sep 17 00:00:00 2001 From: Pavel Forkert Date: Sun, 27 Feb 2011 23:40:10 +0200 Subject: [PATCH] Added test case and fix for proper eager loading associations --- .../lib/active_record/association_preload.rb | 3 ++- activerecord/test/cases/associations/eager_test.rb | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb index f5d6eef..41dc0ad 100644 --- a/activerecord/lib/active_record/association_preload.rb +++ b/activerecord/lib/active_record/association_preload.rb @@ -85,7 +85,7 @@ module ActiveRecord # 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 @@ module ActiveRecord 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 diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index bcf7b29..c9c0fde 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -156,6 +156,16 @@ class EagerAssociationTest < ActiveRecord::TestCase 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 -- 1.7.3.1