Search code examples
ruby-on-railsmodel-associations

Can you use "belongs_to' if a model can be associated to multiple owners/parents?


I have a many-to-many relationship between Policy(s) and Rule(s). A policy can have multiple rules. A given rule can belong to multiple policies. There's a mapping table PolicyRule(s) that exists (plus other metadata about the relation). From what I understand doing has_and_belongs_to_many would not work if the mapping table has other columns. So I'm looking into doing a has_many :through. This doc has an example of Document -> Section -> Paragraphs that I'm following but I'm not sure if it's correct for me to say that rule belongs_to: policy_rule when it can belong to more than one.

class Policy < Base
    has_many :rule, through: :policy_rule
end

class PolicyRule < Base
    belongs_to :policy
    has_many :rules
end

class Rule < Base
    belongs_to: :policy_rule
end


Solution

  • You need to define these associations

    class Policy < Base
      has_many :policy_rules
      has_many :rules, through: :policy_rules
    end
    
    class PolicyRule < Base
      belongs_to :policy
      belongs_to :rule
    end
    
    class Rule < Base
      has_many :policy_rules
      has_many :policies, through: :policy_rules
    end
    

    And then you can get all rules for one policy and all policies for one rule.

    policy = Policy.find(1)
    policy.rules
    
    rule = Rule.find(1)
    rule.policies
    

    Also you can create new records like this:

    policy = Policy.find(1)
    policy.rules.create(rule_params)
    
    rule = Rule.find(1)
    rule.policies.create(policy_params)
    

    And many other operations. Refer to these docs Active Record Associations