Bugfix ActiveRecord::Relation#merge special case of from clause

When one relation is merged into another that has a different base class
merging `from_clause` causes invalid SQL to be generated
This commit is contained in:
Bogdan Gusiev 2018-09-28 11:38:15 +03:00
parent 2ab0df00b6
commit d76e3e1280
2 changed files with 10 additions and 3 deletions

View File

@ -171,9 +171,7 @@ module ActiveRecord
end
def merge_clauses
if relation.from_clause.empty? && !other.from_clause.empty?
relation.from_clause = other.from_clause
end
relation.from_clause = other.from_clause if replace_from_clause?
where_clause = relation.where_clause.merge(other.where_clause)
relation.where_clause = where_clause unless where_clause.empty?
@ -181,6 +179,11 @@ module ActiveRecord
having_clause = relation.having_clause.merge(other.having_clause)
relation.having_clause = having_clause unless having_clause.empty?
end
def replace_from_clause?
relation.from_clause.empty? && !other.from_clause.empty? &&
relation.klass.base_class == other.klass.base_class
end
end
end
end

View File

@ -122,6 +122,10 @@ class RelationMergingTest < ActiveRecord::TestCase
assert_not_empty relation.from_clause
end
def test_merging_with_from_clause_on_different_class
assert Comment.joins(:post).merge(Post.from("posts")).first
end
def test_merging_with_order_with_binds
relation = Post.all.merge(Post.order([Arel.sql("title LIKE ?"), "%suffix"]))
assert_equal ["title LIKE '%suffix'"], relation.order_values