Search code examples
ruby-on-railsbelongs-tomodel-associations

What type of relations to choose if I want to link 2 models with one


I have model Message. It may be posted by either Person or Organization from my DB. I want to call update.contact, where contact is Organization or Person.

class Update < ActiveRecord::Base
has_one :contact

The decision I like to use is like

class Organization < ActiveRecord::Base
belongs_to :update, as: :contact

But this approach not available in Rails. Should I use polymorphic association? How to organize the architecture for this case?


Solution

  • It sounds like Organization and Person might be two different variants of a same entity (a customer, user, whatever). So, why not create a common parent model for the two of them? Such a parent wouldn't necessarily need a table, and you might just define common methods inside of it. Update is more of an action rather than an object, which could be applied to a Contact object (typically in its controller). For the Contact class, polymorphic association can be used. So you might have:

    class Parent < ActiveRecord::Base
    
    # stuff Person and Organization share
    
    end
    
    class Person < Parent
    
    has_one :contact, as: :owner
    
    # Person methods etc.
    
    end
    
    class Organization < Parent
    
    has_one :contact, as: :owner
    
    # Organization stuff
    
    end
    
    class Contact
    
    belongs_to :owner, polymorphic: true
    
    def update
    #...
    end
    
    # other stuff for Contact
    
    end
    

    Then you can write lines like:

    Person.first.contact.update
    

    or whatever you need to do with your objects.

    In case your Organization and Person don't differ too much, you could just create a table for the parent class, and add the has_one etc. in there.