简体   繁体   中英

Associating two models in different ways

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

  • user can create a rule
  • user can assign a rule to another user

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM