Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

belongs_to not using primary key option

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

like image 925
FearMediocrity Avatar asked Aug 01 '09 16:08

FearMediocrity


2 Answers

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

like image 94
Peer Allan Avatar answered Nov 20 '22 12:11

Peer Allan


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

like image 35
FearMediocrity Avatar answered Nov 20 '22 12:11

FearMediocrity