Model belongs_to eiher/or more than one models

 ̄綄美尐妖づ 提交于 2020-01-14 19:58:28

问题


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.

I have set up the following associations

In person.rb:

has_many :subscriptions

In group.rb:

has_many :subscriptions

In subscription.rb:

belongs_to :person
belongs_to :group

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?

I would rather avoid using polymorphic associations if not absolutely necessary.


回答1:


Yes a model can belong to more than one model.

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

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, optional: true




回答2:


Yes you can use belongs_to for more than one model

also you can use polymorphic association for same

consider following example, where address can be belongs to multiple models

class Subscription < ApplicationRecord
    belongs_to :resource, polymorphic: true
end

and for other models use has_one or has_many association

has_many :subscriptions, foreign_key: :resource_id

Note: resource_id and resource_type columns are required to be added in subscriptions table



来源:https://stackoverflow.com/questions/48486797/model-belongs-to-eiher-or-more-than-one-models

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