This project is archived and is in readonly mode.

#538 ✓invalid

has_many :through generates bad SQL during include?

Reported by ...Paul | July 2nd, 2008 @ 07:14 PM | in 2.x

If I have a class that has_many of another class :through a join table, I find I get a SQL error from the .include?(obj) method. This doesn't happen if the related data is already loaded.

class Channel < ActiveRecord::Base

has_many :users, :through => :subscriptions


u = User.find(:first)

c = Channel.find(:first)


Mysql::Error: Column 'id' in where clause is ambiguous: SELECT `users`.id FROM `users1` INNER JOIN subscriptions ON = subscriptions.user_id WHERE (id = 19) AND ((`subscriptions`.channel_id = 54)) LIMIT 1




This code worked fine before upgrading to 2.1. I can't seem to find where this bare "id" in the WHERE clause could be coming from...

Comments and changes to this ticket

  • ...Paul

    ...Paul July 2nd, 2008 @ 07:41 PM

    The problem exists somewhere in the heirarchy of the "exists?" method in active_record/base.rb (or, in active_record/associations/association_collection.rb, where exists? is called from the include? method, passing only the record to be searched for).

    I found if I kludged the include? method so the exists call looked like this:

    exists?(["#{quoted_table_name}.#{primary_key} = ?",])

    Things worked for me, at least in this case. I'm fairly certain that's not a really a good patch, but it confirmed my suspicions that something in that heirarchy isn't properly using the table name space in the query. :P

  • Tarmo Tänav

    Tarmo Tänav September 18th, 2008 @ 07:45 AM

    • State changed from “new” to “invalid”

    I'm unable to reproduce it, looking at sanitize_sql_hash_for_conditions() which exists?() calls indirectly through expand_id_conditions() it seems that everything should get properly prefixed with a table name.

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