Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_many :through generates bad SQL during include?

#538

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

end

u = User.find(:first)

c = Channel.find(:first)

c.users.include?(u)

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

>c.users

>c.users.include?(u)

true

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...

Reported by ...Paul · July 2nd, 2008 @ 07:14 PM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. ...Paul
    ...Paul

    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} = ?", record.id])

    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

    July 2nd, 2008 @ 07:41 PM

  2. Tarmo Tänav
    Tarmo Tänav
    • 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.

    September 18th, 2008 @ 07:45 AM