R – belongs_to not using primary key option

activerecordruby-on-rails

I've been struggling with this for a while, and decided to throw it out there:

I have 3 models, User, Connection, Suspect

A User has many Connections,
A Connection has one Suspect, linked via case_id

A User has many Suspects through its Connections.

The code is as follows:

class User < ActiveRecord::Base
  has_many :followers
  has_many :suspects, :through => :followers
end

class Connection < ActiveRecord::Base
  belongs_to :user
  belongs_to :suspect, :primary_key => :case_id , :foreign_key => :case_id
end

class Suspect < ActiveRecord::Base
  belongs_to :connection, :primary_key => :case_id , :foreign_key => :case_id
end

The problem is that the belongs_to seems to ignore the :primary key.

If I do

u = User.find(:first)
u.suspects

The SQL generated is:

SELECT `suspects`.* FROM `suspects` INNER JOIN `connections` ON `suspects`.id = `connections`.case_id WHERE ((`followers`.user_id = 1))

However it should be:

SELECT `suspects`.* FROM `suspects` INNER JOIN `connections` ON `suspects`.case_id = `connections`.case_id WHERE ((`followers`.user_id = 1))

Can someone point me in the right direction?

James

Best Answer

The docs for belongs_to say that you can use the :primary_key option, but we have never been able to get it to work either. That said the latest version of rails, 2.3.3, specifically has a fix for this

Related Topic