Skip to content

Commit

Permalink
Relation merging should keep joining order
Browse files Browse the repository at this point in the history
`joins_values.partition` will break joins values order. It should be
kept as user intended order.

Fixes #15488.
  • Loading branch information
kamipo committed Nov 10, 2017
1 parent fc7a6c7 commit 4528dd6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
18 changes: 8 additions & 10 deletions activerecord/lib/active_record/relation/merger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,22 +112,20 @@ def merge_joins
if other.klass == relation.klass
relation.joins!(*other.joins_values)
else
joins_dependency, rest = other.joins_values.partition do |join|
alias_tracker = nil
joins_dependency = other.joins_values.map do |join|
case join
when Hash, Symbol, Array
true
alias_tracker ||= other.alias_tracker
ActiveRecord::Associations::JoinDependency.new(
other.klass, other.table, join, alias_tracker
)
else
false
join
end
end

join_dependency = ActiveRecord::Associations::JoinDependency.new(
other.klass, other.table, joins_dependency, other.alias_tracker
)

relation.joins! rest

@relation = relation.joins join_dependency
relation.joins!(*joins_dependency)
end
end

Expand Down
9 changes: 9 additions & 0 deletions activerecord/test/cases/relation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,15 @@ def test_relation_merging_with_merged_joins_as_strings
assert_equal({ 2 => 1, 4 => 3, 5 => 1 }, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count)
end

def test_relation_merging_keeps_joining_order
authors = Author.where(id: 1)
posts = Post.joins(:author).merge(authors)
comments = Comment.joins(:post).merge(posts)
ratings = Rating.joins(:comment).merge(comments)

assert_equal 3, ratings.count
end

class EnsureRoundTripTypeCasting < ActiveRecord::Type::Value
def type
:string
Expand Down

0 comments on commit 4528dd6

Please sign in to comment.