Rails:非 ID 外键查找 ActiveRecord [英] Rails: Non id foreign key lookup ActiveRecord
问题描述
我希望 ActiveRecord
通过表中的非 id 列进行查找.希望当我给你我的代码示例时,这很清楚.
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
当我做一个coach_obj.coach_classes
,正确触发
SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 2)
(2 是那个教练的 id
,这是我的问题.)
(2 being the that coach's id
here which is my problem.)
我希望它触发
SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 'David')
('David' 是那个教练的 user_name
)
('David' being the that coach's user_name
)
user_name
在两个表中都是唯一的.
user_name
is unique and present in both tables.
出于某种原因,我不想在我的 coach_classes
表中有 coach_id
.
I do not want to have a coach_id
in my coach_classes
table for some reason.
推荐答案
我认为您还需要在关联上指定主键选项:
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
指定返回关联对象主键的方法(默认为id
).
This specifies the method that returns the primary key of the associated object (defaulting to id
).
这篇关于Rails:非 ID 外键查找 ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!