Skip to content
Browse files

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.

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/associations/join_dependency/join_association.rb
  • Loading branch information...
1 parent 38ac28b commit b407839601c8dc7b007a6baddea3696b737c352b @jonleighton jonleighton committed Apr 19, 2013
View
19 activerecord/CHANGELOG.md
@@ -1,5 +1,24 @@
## unreleased ##
+* 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*
+
* `inspect` on Active Record model classes does not initiate a
new connection. This means that calling `inspect`, when the
database is missing, will no longer raise an exception.
View
2 activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -106,6 +106,8 @@ def join_to(manager)
]
end
+ scope_chain_items += [reflection.klass.send(:build_default_scope)].compact
+
scope_chain_items.each do |item|
unless item.is_a?(Relation)
item = ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item)
View
8 activerecord/test/cases/associations/inner_join_association_test.rb
@@ -104,4 +104,12 @@ def test_find_with_conditions_on_through_reflection
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

0 comments on commit b407839

Please sign in to comment.
Something went wrong with that request. Please try again.