模型属于一个/或多个模型 [英] Model belongs_to eiher/or more than one models

查看:41
本文介绍了模型属于一个/或多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能有一个模型属于(或/或)多个模型?

Is it possible to have a model which belongs_to (either/or) more than one models?

例如,在我的项目中,我有一个订阅模型,它可能属于一个人或一个组.当一个人加入特定群组时,她会自动继承"该群组的订阅.

For example, in my project I have a subscription model that may belong to a person or a group. When a person will join a particular group she automatically "inherits" the subscriptions of that group.

我已经建立了以下关联

亲自.rb:

has_many :subscriptions

在 group.rb 中:

In group.rb:

has_many :subscriptions

在订阅.rb:

belongs_to :person
belongs_to :group

此外,我在订阅表中添加了 person_id 和 group_id 字段.

Also, I have added fields for person_id and group_id in the subscriptions table.

问题是,当我尝试与某个人创建订阅时,我收到一个错误,提示组必须存在".

The problem is that when I try to create a subscription with let's say a person I get an error that the "Group must exist".

有没有办法克服这个问题?

Is there a way to overcome this?

如果不是绝对必要,我宁愿避免使用多态关联.

推荐答案

是的,一个模型可以属于多个模型.

Yes a model can belong to more than one model.

belongs_to 现在,如果关联不存在,rails 中的默认情况下将触发验证错误.

belongs_to in rails will now trigger a validation error by default if the association is not present.

我们可以在每个关联的基础上使用 optional: true 关闭它.您必须声明订阅关联belongs_to 组为可选

We can turn this off on a per-association basis with optional: true. You have to declare the subscription association belongs_to group as optional

belongs_to :class,可选:true

这篇关于模型属于一个/或多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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