Rails:非 id 外键查找 ActiveRecord
我希望 ActiveRecord 通过表中的非 id 列进行查找。 希望当我向您提供代码示例时您能清楚地了解这一点。
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
,这是我的问题。)
我希望它触发
SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 'David')
(“David”是那个教练的>user_name
)
user_name
是唯一的并且存在于两个表中。
由于某种原因,我不想在我的 coach_classes
表中包含 coach_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
When I do acoach_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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您还需要指定关联的主键选项:
这指定返回关联对象的主键的方法(默认为
id
)。I think you need to specify the primary key options on the associations as well:
This specifies the method that returns the primary key of the associated object (defaulting to
id
).有一个名为
primary_key
的选项,默认设置为:id
。您想要使用:同时在
belongs_to
关联上使用这些选项。请参阅文档了解更多信息。
There is a option called
primary_key
which is per default set to:id
. You want to use:Also use these options on the
belongs_to
association.Read more in the documentation.
您需要使用
finder_sql
:You need to use
finder_sql
: