Rails中两个表之间的2个或多个一对多关系 [英] 2 or more One to Many relationships between two tables in rails

查看:72
本文介绍了Rails中两个表之间的2个或多个一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表:

用户和组

一个用户有多个组和一个组,属于一个用户:

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

u = User.last
u.groups 

假设出于某些奇怪的原因,我想要第二个不同组的列表.用户再次具有可能的组(在此示例中称为other_group),并且组属于用户.

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

如何在两次关联中使用Active Record关联两次模型?

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

推荐答案

您可以

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

这篇关于Rails中两个表之间的2个或多个一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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