views:

396

answers:

2

Hello,

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

+3  A: 

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

Peer Allan
Has it been fixed yet in 3.0? I'm getting the same problem.
mohawkjohn
+1  A: 

After more testing, @pallan is correct, this was fixed in 2.3.3 but only for the first level of association, not for has_many :through.

For example:

Connection.suspects

Uses the correct SQL, but

User.connections.suspects

Does not.

I'm going to open a ticket for it now.

JP

FearMediocrity