Permalink
Browse files

Merge pull request #9252 from senny/8423_hmt_preloading_bug

don't cache invalid subsets when preloading hmt associations
Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/cases/associations/eager_test.rb
  • Loading branch information...
1 parent ee3e3a9 commit c5451777b038c5e48567f69256986ae42a2cde48 @rafaelfranca rafaelfranca committed Feb 14, 2013
View
@@ -1,3 +1,25 @@
+* Preloading `has_many :through` associations with conditions won't
+ cache the `:through` association. This will prevent invalid
+ subsets to be cached.
+ Fixes #8423.
+
+ Example:
+
+ class User
+ has_many :posts
+ has_many :recent_comments, -> { where('created_at > ?', 1.week.ago) }, :through => :posts
+ end
+
+ a_user = User.includes(:recent_comments).first
+
+ # this is preloaded
+ a_user.recent_comments
+
+ # fetching the recent_comments through the posts association won't preload it.
+ a_user.posts
+
+ *Yves Senn*
+
* Fix counter cache columns not updated when replacing `has_many :through`
associations.
Backport #8400.
@@ -37,7 +37,8 @@ def through_records_by_owner
through_records = Array.wrap(owner.send(through_reflection.name))
# Dont cache the association - we would only be caching a subset
- if reflection.options[:source_type] && through_reflection.collection?
+ if (through_scope != through_reflection.klass.unscoped) ||
+ (reflection.options[:source_type] && through_reflection.collection?)
@n1zyy

n1zyy Feb 15, 2013

through_scope doesn't appear to be defined on 3-2-stable where this was just merged. Looks like the method came in with commit 65843e1 which seems to exist only on master.

@rafaelfranca

rafaelfranca Feb 15, 2013

Owner

@senny could you take a look please. In meanwhile I'll revert this backport

@senny

senny Feb 15, 2013

Member

I'll take a look and submit a valid backport.

owner.association(through_reflection.name).reset
end
@@ -1112,4 +1112,10 @@ def test_join_eager_with_nil_order_should_generate_valid_sql
Post.includes(:comments).order(nil).where(:comments => {:body => "Thank you for the welcome"}).first
end
end
+
+ test "preloading does not cache has many association subset when preloaded with a through association" do
+ author = Author.includes(:comments_with_order_and_conditions, :posts).first
+ assert_no_queries { assert_equal 2, author.comments_with_order_and_conditions.size }
+ assert_no_queries { assert_equal 5, author.posts.size, "should not cache a subset of the association" }
+ end
end

0 comments on commit c545177

Please sign in to comment.