Rails: Non id foreign key lookup ActiveRecord

Garfield picture Garfield · Jul 23, 2010 · Viewed 14.2k times · Source

I want ActiveRecord to lookup by a non-id column from a table. Hope this is clear when I give you my code sample.

class CoachClass < ActiveRecord::Base
  belongs_to :coach
end

class Coach < ActiveRecord::Base
    has_many :coach_classes, :foreign_key => 'user_name'
end

When I do a coach_obj.coach_classes, this rightly triggers

SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 2)

(2 being the that coach's id here which is my problem.)

I want it to trigger

SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 'David')

('David' being the that coach's user_name)

user_name is unique and present in both tables.

I do not want to have a coach_id in my coach_classes table for some reason.

Answer

John Topley picture John Topley · Jul 23, 2010

I think you need to specify the primary key options on the associations as well:

class CoachClass < ActiveRecord::Base 
  belongs_to :coach, :foreign_key => 'user_name', :primary_key => 'user_name'
end

class Coach < ActiveRecord::Base
  has_many :coach_classes, :foreign_key => 'user_name', :primary_key => 'user_name'
end 

This specifies the method that returns the primary key of the associated object (defaulting to id).