Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implicit through table joins should be appeared before user supplied joins #36304

Merged
merged 1 commit into from
May 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 11 additions & 17 deletions activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1128,27 +1128,21 @@ def build_join_query(manager, buckets, join_type, aliases)

association_joins = buckets[:association_join]
stashed_joins = buckets[:stashed_join]
join_nodes = buckets[:join_node].uniq
string_joins = buckets[:string_join].map(&:strip).uniq
join_nodes = buckets[:join_node].tap(&:uniq!)
string_joins = buckets[:string_join].delete_if(&:blank?).map!(&:strip).tap(&:uniq!)

join_list = join_nodes + convert_join_strings_to_ast(string_joins)
alias_tracker = alias_tracker(join_list, aliases)
string_joins.map! { |join| table.create_string_join(Arel.sql(join)) }

join_dependency = construct_join_dependency(association_joins, join_type)
join_sources = manager.join_sources
join_sources.concat(join_nodes) unless join_nodes.empty?

joins = join_dependency.join_constraints(stashed_joins, alias_tracker)
joins.each { |join| manager.from(join) }

manager.join_sources.concat(join_list)

alias_tracker.aliases
end
unless association_joins.empty? && stashed_joins.empty?
alias_tracker = alias_tracker(join_nodes + string_joins, aliases)
join_dependency = construct_join_dependency(association_joins, join_type)
join_sources.concat(join_dependency.join_constraints(stashed_joins, alias_tracker))
end

def convert_join_strings_to_ast(joins)
joins
.flatten
.reject(&:blank?)
.map { |join| table.create_string_join(Arel.sql(join)) }
join_sources.concat(string_joins) unless string_joins.empty?
end

def build_select(arel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ def test_marshal_dump
assert_equal preloaded, Marshal.load(Marshal.dump(preloaded))
end

def test_through_association_with_joins
assert_equal [comments(:eager_other_comment1)], authors(:mary).comments.merge(Post.joins(:comments))
end

def test_through_association_with_left_joins
assert_equal [comments(:eager_other_comment1)], authors(:mary).comments.merge(Post.left_joins(:comments))
end

def test_preload_with_nested_association
posts = Post.preload(:author, :author_favorites_with_scope).to_a

Expand Down