From 0963774c0a6a58ba13ac0ff4763527ea7d994c0a Mon Sep 17 00:00:00 2001 From: Grant Ammons Date: Mon, 28 Jun 2010 18:59:21 -0400 Subject: [PATCH] fixes #2362, eager loading :through associations will join the :source model if there are :conditions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/lib/active_record/association_preload.rb | 6 +++++- activerecord/test/cases/associations/eager_test.rb | 7 +++++++ activerecord/test/models/post.rb | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb index 487a2bb3ac359..c2206dcd76cef 100644 --- a/activerecord/lib/active_record/association_preload.rb +++ b/activerecord/lib/active_record/association_preload.rb @@ -282,7 +282,11 @@ def preload_through_records(records, reflection, through_association) end through_records.flatten! else - records.first.class.preload_associations(records, through_association) + options = {} + options[:include] = reflection.options[:include] || reflection.options[:source] if reflection.options[:conditions] + options[:order] = reflection.options[:order] + options[:conditions] = reflection.options[:conditions] + records.first.class.preload_associations(records, through_association, options) through_records = records.map {|record| record.send(through_association)}.flatten end through_records.compact! diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 9d3be8de9b2b1..1870f97620611 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -357,6 +357,13 @@ def test_eager_with_has_many_through_join_model_with_conditions_on_top_level assert_equal comments(:more_greetings), Author.find(authors(:david).id, :include => :comments_with_order_and_conditions).comments_with_order_and_conditions.first end + def test_eager_with_has_many_through_with_conditions_join_model_with_include + post_tags = Post.find(posts(:welcome).id).misc_tags + eager_post_tags = Post.find(1, :include => :misc_tags).misc_tags + assert_equal post_tags, eager_post_tags + end + + def test_eager_with_has_many_through_join_model_with_include author_comments = Author.find(authors(:david).id, :include => :comments_with_include).comments_with_include.to_a assert_no_queries do diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 315ad008130c8..cf69d049be272 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -53,6 +53,7 @@ def add_joins_and_select end end + has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => "tags.name = 'Misc'" has_many :funky_tags, :through => :taggings, :source => :tag has_many :super_tags, :through => :taggings has_one :tagging, :as => :taggable