两个表上的 Rails 自定义外键名称 [英] Rails custom foreign_key name on both table

查看:37
本文介绍了两个表上的 Rails 自定义外键名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,例如 User 和 Club 及其属性:

I have two models, for example User and Club with their attributes:

User:
  id
  uid
  email
  etc.

Club:
  id
  player_id
  address
  supporter
  etc.

出于某种原因,加入属性是 clubs.player_idusers.uid 而不是 clubs.player_idusers.id.是否可以使用 has_onebelongs_to 将这两个模型与 one-to-one 关联连接起来?谢谢

For some reason, the join attribute is clubs.player_id with users.uid NOT clubs.player_id with users.id. Is it possible connecting these two model with one-to-one association using has_one and belongs_to? thx

推荐答案

我敢打赌这会奏效:

class User < ActiveRecord::Base
  has_one :club, :foreign_key => :player_id, :primary_key => :uid
end

class Club < ActiveRecord::Base
  belongs_to :user, :foreign_key => :player_id, :primary_key => :uid
end

这篇关于两个表上的 Rails 自定义外键名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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