This project is archived and is in readonly mode.

#4463 ✓committed
Ernie Miller

JoinAssociation#aliased_table_name_for bug affecting AR find_with_associations?

Reported by Ernie Miller | April 23rd, 2010 @ 04:11 PM | in 3.0.2

While working on a gem, I was making use of the JoinDependency feature where you can supply some existing SQL on initialization to keep aliased_table_name_for from reusing table names in those joins. I encountered a problem in the interaction between aliased_table_name_for, find_with_associations (finder_methods.rb), and build_arel (query_methods.rb)

First: aliased_table_name_for looks at parent#table_joins for this SQL, but therefore only correctly detects table names used outside of the JoinDependency for a top-level join, since this join_sql is not passed down through associations when calling "super(reflection.klass)" in JoinAssociation#initialize.

Second: the order in which build_arel (query_methods.rb) builds a query reverses the "simulated" JoinDependency used to create the outer joins added by find_with_associations, and so ends up reusing column names anyway, regardless of that fact.

This leads to (where Article has_many :comments, has_many :moderations, :through => :comments):

Article.joins(:comments).eager_load(:moderations) ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: comments.article_id ...

The fix as I see it involves determining the user-supplied joins in advance of any association joins and supplying that SQL to in build_arel to prevent table name collisions.

I have this fixed in my gem at and would be happy to port the fix to a patch with tests if this is confirmed as a bug.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket

Referenced by