2 or more One to Many relationships between two tables in rails

五迷三道 提交于 2019-12-08 06:41:03

问题


I have two tables:

Users and Groups

a User has_many groups and a group, belongs_to a user:

u = User.last
u.groups 

Supposed I wanted a second list of different groups, for some strange reason. Where once again a User has may groups (called other_group in this example) and a group belongs to a User.

u = User.last
u.other_groups

How do I associate two models in this relationship, Twice using Active Record?


回答1:


You can do

class User
    has_many :groups, :class_name => "Group", :foreign_key => "group_id"
    has_many :other_groups, :class_name => "Group", :foreign_key => "other_group_id"



回答2:


Your User model could have two foreign keys (attributes in rails)

User.group_id
User.other_group_id



回答3:


You can do

User(user_id)  
Group(group_id)
UserGroup (id, user_id, group_id)

this allows you to have records with user_ids associated for different groups.
This way lets you have multiple user-group associations.



来源:https://stackoverflow.com/questions/30468368/2-or-more-one-to-many-relationships-between-two-tables-in-rails

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