diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 7cfbda747f..29853b2228 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -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* diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index b81aecb4e5..e0715d9dd1 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -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) diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 9baf94399a..de47a576c6 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -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