Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
don't cache invalid subsets when preloading hmt associations.
closes #8423.
  • Loading branch information
senny committed Feb 14, 2013
1 parent 1fd7830 commit 4a4ff50
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
22 changes: 22 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,5 +1,27 @@
## Rails 4.0.0 (unreleased) ##

* 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*

* Don't run after_commit callback when creating through an association
if saving the record fails.

Expand Down
Expand Up @@ -31,7 +31,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?)
owner.association(through_reflection.name).reset
end

Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/associations/eager_test.rb
Expand Up @@ -1162,4 +1162,10 @@ def test_deep_including_through_habtm
Post.where('1 = 0').scoping { Comment.preload(:post).find(1).post }
)
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 4a4ff50

Please sign in to comment.