In the situation where a table appears twice in a finder query:
- firstly as an intermediate join in a habtm / has_many :through association, and
- secondly, appearing in a cascaded eager loading clause anywhere deeper than the top level;
the table does not receive a unique table alias when the eager loading clause is constructed. For example:
class Author < ActiveRecord::Base
has_many :comments_with_cited_posts, :through => :posts
end
class Post < ActiveRecord::Base
has_many :comments_with_cited_posts, :class_name => "Comment",
:include => {:post_citations => :post}
end
In the Author#comments_with_cited_posts query, the 'posts' table is joined twice but does not get aliased as part of the eager loading.
As far as I can tell, this is due to the following snippet in associations.rb:
if !parent.table_joins.blank? && parent.table_joins.to_s.downcase =~ %r{join(\s+\w+)?\s+#{aliased_table_name.downcase}\son}
join_dependency.table_aliases[aliased_table_name] += 1
end
which is supposed to scan the SQL for an existing join on 'posts', but at that point parent.table_joins is blank, presumably because 'parent' refers to the :post_citations association rather than the query as a whole.
Test case attached.