Permalink
Browse files

Correctly handle joining scoped associations with table aliases.

Backport of #14154 to 4-0-stable.
  • Loading branch information...
1 parent 0ce2e90 commit 42627970e2e24fcd8f2c43353d7169dae2a5791c @al2o3cr al2o3cr committed with chancancode Apr 18, 2014
@@ -1,3 +1,10 @@
+* When joining tables with a default scope, ensure the generated table name
+ in the ON conditions from the default scope is correctly aliased .
+
+ Backports #14154.
+
+ *Matt Jones*
+
* Fix name collision with `Array#select!` with `Relation#select!`.
Fixes #14752.
@@ -106,7 +106,7 @@ def join_to(manager)
]
end
- scope_chain_items += [reflection.klass.send(:build_default_scope)].compact
+ scope_chain_items += [reflection.klass.send(:build_default_scope, ActiveRecord::Relation.new(reflection.klass, table))].compact
scope_chain_items.each do |item|
unless item.is_a?(Relation)
@@ -102,15 +102,15 @@ def default_scope(scope = nil)
self.default_scopes += [scope]
end
- def build_default_scope # :nodoc:
+ def build_default_scope(base_rel = relation) # :nodoc:
if !Base.is_a?(method(:default_scope).owner)
# The user has defined their own default scope method, so call that
evaluate_default_scope { default_scope }
elsif default_scopes.any?
evaluate_default_scope do
- default_scopes.inject(relation) do |default_scope, scope|
+ default_scopes.inject(base_rel) do |default_scope, scope|
if !scope.is_a?(Relation) && scope.respond_to?(:call)
- default_scope.merge(unscoped { scope.call })
+ default_scope.merge(base_rel.scoping { scope.call })
else
default_scope.merge(scope)
end
@@ -117,4 +117,13 @@ def test_find_with_conditions_on_through_reflection
assert_equal [author], Author.where(id: author).joins(:special_categorizations)
end
+
+ test "the default scope of the target is correctly aliased when joining associations" do
+ author = Author.create! name: "Jon"
+ author.categories.create! name: 'Not Special'
+ author.special_categories.create! name: 'Special'
+
+ categories = author.categories.includes(:special_categorizations).references(:special_categorizations).to_a
+ assert_equal 2, categories.size
+ end
end
@@ -22,6 +22,7 @@ def self.what_are_you
end
has_many :categorizations
+ has_many :special_categorizations
has_many :post_comments, :through => :posts, :source => :comments
has_many :authors, :through => :categorizations

0 comments on commit 4262797

Please sign in to comment.