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
This commit is contained in:
Aaron Patterson 2014-11-07 16:23:15 -08:00
parent a450cac35e
commit c2fc9848b1
2 changed files with 28 additions and 1 deletions

View File

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

View File

@ -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')