This project is archived and is in readonly mode.
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
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...
Comments and changes to this ticket
-
...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} = ?", 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
-
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="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>