I have three classes defined like this: class Campaign < ActiveRecord::Base has_many :urls, :foreign_key => 'campaignid' has_many :stats, :through => :urls set_table_name 'campaign' set_primary_key 'campaignid' end class Url < ActiveRecord::Base belongs_to :campaign, :foreign_key => 'campaignid' has_many :stats, :foreign_key => 'urlid' set_table_name 'url' set_primary_key 'urlid' end class Stat < ActiveRecord::Base belongs_to :url, :foreign_key => 'urlid' set_primary_key 'statsid' end When I drop into the console and try this: >> c = Campaign.find(:first) >> c.stats I get this: ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'url.statsid' in 'on clause': SELECT `stats`.* FROM `stats` INNER JOIN url ON stats.urlid = url.statsid WHERE ((`url`.campaignid = 1)) from /Library/Ruby/Gems/1.8/gems/activerecord-2.1.0/lib/active_record/connection_adapters/abstract_adapter.rb:147:in `log' It looks like the inner join is being improperly constructed. It should say INNER JOIN ON stats.urlid = url.urlid Or, to put it more generically: INNER JOING ON <association_table>.<intermediate_table_fk> = <intermediate_table>.<intermediate_table_pk> But it is currently doing: INNER JOING ON <association_table>.<intermediate_table_fk> = <intermediate_table>.<associate_table_pk> I think this boils down to activerecord-2.1.0/lib/active_record/associations/has_many_through_association.rb:150-155 I think this would be easy to miss since :through associations aren't entirely common and renaming your primary key is also not common so any table's primary key is getting used. I'm going to do a workaround that doesn't use the :through association for now.
on 2008-07-16 23:48
on 2008-07-19 13:18
> I think this would be easy to miss since :through associations aren't > entirely common and renaming your primary key is also not common so any > table's primary key is getting used. I'm going to do a workaround that > doesn't use the :through association for now. Hi there, this definitely sounds like you've found a bug. The best bet would be to jump into the #rails-contrib irc channel on freenode, and ask for some help coming up with a patch to fix this, and include tests. The mechanics of contributing a git patch are covered in: http://rails.lighthouseapp.com/projects/8994/sending-patches -- Cheers Koz