Ryan Castillo
Ryan Castillo

Reputation: 1125

How to build associations for multiple roles?

I'm building a Rails application with multiple roles. I can't use inheritance against the user model because each role has very different properties and behavior (ie - different page access and abilities once logged in). So I've decided to build separate models for each role (ie - customer, service provider, customer representative, etc).

How would the associations for this work? I came up with the following but the Role class just looks bad to me. It wouldn't be so bad if the User could have multiple roles but since they only have one I'd have to write a custom validation in Role ensuring that only one role was selected. What do you guys think?

class User < ActiveRecord::Base
  has_one :role
end

class Role < ActiveRecord::Base
  has_one :customer
  has_one :service_provider
  has_one :customer_representative
end

class Customer < ActiveRecord::Base
end

class ServiceProvider < ActiveRecord::Base
end

class CustomerRepresentative < ActiveRecord::Base
end

Upvotes: 4

Views: 742

Answers (1)

TheDelChop
TheDelChop

Reputation: 7998

I think the problem here is with your "Role" model. The role isn't actually a physical thing, but an interface that other objects should adhere to. Therefore, its a polymorphic relationship.

class User < ActiveRecord::Base
  belongs_to :role, polymorphic: true
end

class Customer < ActiveRecord::Base
  has_one :user, as: :role
end

class ServiceProvider < ActiveRecord::Base
  has_one :user, as: :role
end

class CustomerRepresentative < ActiveRecord::Base
  has_one :user, as: role
end

Then you need to add role_id and role_type to your user table.

This should get your what you want I believe.

Joe

Upvotes: 5

Related Questions