Search code examples
ruby-on-railsrubyassociationsmodels

How to setup a polymorphic association of People and Users?


If there a People model, how can I setup a polymorphic association of Users and Customer?

For example, a Person could act as an User or as a Customer. People could be a User( extra columns: username, password), or it could be a Customer(no extra columns).

I'm trying to set this up so

  1. I won't have a separate Users table and Customers table
  2. I don't want to have a People table with a lot of empty username and password columns

Solution

  • I agree with moo-juice, the correct approach would be people + roles. here's a concrete example:

    class Person < ActiveRecord::Base
      has_many :roles, :through => :roles_people
      #columns would be username, password, etc
    end
    
    class Role < ActiveRecord::Base
      has_many :people, :through > :roles_people
      #a column of role_type would be required here and the values of such would be Customer, User, etc.  in this class you will put logic that is needed to execute the functions of the role
    end
    
    class RolesPerson < ActiveRecord::Base
       belongs_to :person
       belongs_to :role
       #this is a join model for a many-to-many relationship. you can store info in here about when a person acquired a certain role, etc.
    end