3

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.

fool-dev
  • 7,671
  • 9
  • 40
  • 54
kouroubel
  • 260
  • 4
  • 18

2 Answers2

4

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

iamcaleberic
  • 913
  • 8
  • 12
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

Ganesh
  • 1,924
  • 1
  • 18
  • 31