Skip to content

Commit

Permalink
Referencing a table via the ON condition in a join should force that …
Browse files Browse the repository at this point in the history
…table to be eager-loaded via a JOIN rather than via subsequent queries.
  • Loading branch information
jonleighton authored and tenderlove committed Mar 7, 2011
1 parent 9cee693 commit 532f915
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
13 changes: 12 additions & 1 deletion activerecord/lib/active_record/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -407,8 +407,19 @@ def method_missing(method, *args, &block)
private

def references_eager_loaded_tables?
joined_tables = arel.join_sources.map do |join|
if join.is_a?(Arel::Nodes::StringJoin)
tables_in_string(join.left)
else
[join.left.table_name, join.left.table_alias]
end
end

joined_tables += [table.name, table.table_alias]

# always convert table names to downcase as in Oracle quoted table names are in uppercase
joined_tables = (tables_in_string(arel.join_sql) + [table.name, table.table_alias]).compact.map{ |t| t.downcase }.uniq
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq

(tables_in_string(to_sql) - joined_tables).any?
end

Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/relations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -850,4 +850,19 @@ def test_removing_limit_with_options
def test_primary_key
assert_equal "id", Post.scoped.primary_key
end

def test_eager_loading_with_conditions_on_joins
scope = Post.includes(:comments)

# This references the comments table, and so it should cause the comments to be eager
# loaded via a JOIN, rather than by subsequent queries.
scope = scope.joins(
Post.arel_table.create_join(
Post.arel_table,
Post.arel_table.create_on(Comment.arel_table[:id].eq(3))
)
)

assert scope.eager_loading?
end
end

0 comments on commit 532f915

Please sign in to comment.