Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #9322 from senny/backport_9252

don't cache invalid subsets when preloading hmt associations.
  • Loading branch information...
commit b4e053e867232e28c7b99b0d935161d1e4559ced 2 parents 46b65ba + 587f563
@rafaelfranca rafaelfranca authored
View
23 activerecord/CHANGELOG.md
@@ -1,5 +1,28 @@
## unreleased ##
+* Preloading `has_many :through` associations with conditions won't
+ cache the `:through` association. This will prevent invalid
+ subsets to be cached.
+ Fixes #8423.
+ Backport #9252.
+
+ 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 handling of dirty time zone aware attributes
Previously, when `time_zone_aware_attributes` were enabled, after
View
3  activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -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 (preload_options != through_options) ||
+ (reflection.options[:source_type] && through_reflection.collection?)
owner.association(through_reflection.name).reset
end
View
6 activerecord/test/cases/associations/eager_test.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.