diff options
author | Aaron Patterson <aaron.patterson@gmail.com> | 2014-11-07 16:23:15 -0800 |
---|---|---|
committer | Aaron Patterson <aaron.patterson@gmail.com> | 2014-11-07 16:23:15 -0800 |
commit | c2fc9848b1495768a4c550e4cc532882146902c9 (patch) | |
tree | f08d7a70e32d0b7ff77937d1a4545e1ec0545077 | |
parent | a450cac35e29cd810c8daef698478b99d14b9206 (diff) | |
download | rails-c2fc9848b1495768a4c550e4cc532882146902c9.tar.gz rails-c2fc9848b1495768a4c550e4cc532882146902c9.tar.bz2 rails-c2fc9848b1495768a4c550e4cc532882146902c9.zip |
default scopes should break the cache on has_many.
if you specify a default scope on a model, it will break caching. We
cannot predict what will happen inside the scope, so play it safe for
now. fixes #17495
-rw-r--r-- | activerecord/lib/active_record/associations/collection_association.rb | 3 | ||||
-rw-r--r-- | activerecord/test/cases/associations/has_many_associations_test.rb | 26 |
2 files changed, 28 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index bdfd569be2..4411e5ae62 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -409,7 +409,8 @@ module ActiveRecord def get_records if reflection.scope_chain.any?(&:any?) || scope.eager_loading? || - klass.current_scope + klass.current_scope || + klass.default_scopes.any? return scope.to_a end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index fdbe411f86..1617e883ba 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -76,6 +76,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase dev.developer_projects.map(&:project_id).sort end + def test_default_scope_on_relations_is_not_cached + counter = 0 + posts = Class.new(ActiveRecord::Base) { + self.table_name = 'posts' + self.inheritance_column = 'not_there' + post = self + + comments = Class.new(ActiveRecord::Base) { + self.table_name = 'comments' + self.inheritance_column = 'not_there' + belongs_to :post, :class => post + default_scope -> { + counter += 1 + where("id = :inc", :inc => counter) + } + } + has_many :comments, :class => comments, :foreign_key => 'post_id' + } + assert_equal 0, counter + post = posts.first + assert_equal 0, counter + sql = capture_sql { post.comments.to_a } + post.comments.reset + assert_not_equal sql, capture_sql { post.comments.to_a } + end + def test_has_many_build_with_options college = College.create(name: 'UFMT') Student.create(active: true, college_id: college.id, name: 'Sarah') |