Kumar
Kumar

Reputation: 3126

Associating two models in different ways

I have two models. user & rule
and two different cases

For first case I'm doing:

class User
  has_many :rules #owner or the rule
end

class Rule
  belongs_to :user
end

For second case: (rule can also be applied to other models, so I've made it polymorphic)

class User
  has_many :rules, as: :rulable #rules applied to the user
end

class Rule
  belongs_to :rulable, polymorphic: true
end

Now if I want to get rules created by a user, and rules applied to a user separately, how would I go about it.

Upvotes: 0

Views: 35

Answers (1)

Deepesh
Deepesh

Reputation: 6398

It is never necessary to have the association name same as model name you can define it something else and mention the class name. So in your case you can do like this:

class User
  has_many :rules #owner or the rule
  has_many :rules_applied, as: :rulable, class_name: 'Rule' #rules applied to the user
end

class Rule
  belongs_to :user
  belongs_to :rulable, polymorphic: true
end

So user.rules will return created rules and user.rules_applied will return applied rules.

And rule.user will return the owner and rule.rulable will return the user on which rule is applied.

Upvotes: 1

Related Questions