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
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.
Then you need to add
role_idandrole_typeto your user table.This should get your what you want I believe.
Joe