Rails custom foreign_key name on both table

徘徊边缘 提交于 2019-11-29 14:54:59

问题


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

User:
  id
  uid
  email
  etc.

and

Club:
  id
  player_id
  address
  supporter
  etc.

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


回答1:


I bet this would work:

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



回答2:


Can Clubs have many Users and Users belong to many Clubs? If so, you may want to look at the http://guides.rubyonrails.org/association_basics.html page for the has_and_belongs_to_many relationship association method. If you use this association method, you will need to create a separate migration table to relate the user_id with the club_id.



来源:https://stackoverflow.com/questions/10640941/rails-custom-foreign-key-name-on-both-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!