扶手:无标识外键查找的ActiveRecord [英] Rails: Non id foreign key lookup ActiveRecord

查看:175
本文介绍了扶手:无标识外键查找的ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想的ActiveRecord 来通过从表中的非ID列查找。 希望这是明确的,当我给你我的code样本。

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 ,这正好触发

When I do a coach_obj.coach_classes, this rightly triggers

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')

(大卫作为主教练的用户名

用户名是独一无二的,present两个表。

user_name is unique and present in both tables.

我不希望有一个 coach_id 在我的 coach_classes 表中的某些原因。

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).

这篇关于扶手:无标识外键查找的ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆