Apply default scope when joining associations.

For example:

    class Post < ActiveRecord::Base
      default_scope -> { where published: true }
    end

    class Comment
      belongs_to :post
    end

When calling `Comment.join(:post)`, we expect to receive only
comments on published posts, since that is the default scope for
posts.

Before this change, the default scope from `Post` was not applied,
so we'd get comments on unpublished posts.
This commit is contained in:
Jon Leighton 2013-04-19 12:52:44 +01:00
parent 4642f5487a
commit 55193e449a
3 changed files with 29 additions and 0 deletions

View File

@ -1,3 +1,22 @@
* Apply default scope when joining associations. For example:
class Post < ActiveRecord::Base
default_scope -> { where published: true }
end
class Comment
belongs_to :post
end
When calling `Comment.joins(:post)`, we expect to receive only
comments on published posts, since that is the default scope for
posts.
Before this change, the default scope from `Post` was not applied,
so we'd get comments on unpublished posts.
*Jon Leighton*
* Remove `activerecord-deprecated_finders` as a dependency
*Łukasz Strzałkowski*

View File

@ -106,6 +106,8 @@ module ActiveRecord
]
end
scope_chain_items += [reflection.klass.send(:build_default_scope)].compact
constraint = scope_chain_items.inject(constraint) do |chain, item|
unless item.is_a?(Relation)
item = ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item)

View File

@ -104,4 +104,12 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
assert !posts(:welcome).tags.empty?
assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
end
test "the default scope of the target is applied when joining associations" do
author = Author.create! name: "Jon"
author.categorizations.create!
author.categorizations.create! special: true
assert_equal [author], Author.where(id: author).joins(:special_categorizations)
end
end