两个表上的 Rails 自定义外键名称

两个表上的 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