Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple user roles in Ruby on Rails

I am building an inventory management application with four different user types: admin, employee, manufacturer, transporter. I haven't started coding yet, but this is what I'm thinking.. Manufacturers and transporters are related with has_many :through many-to-many association with products as follows:

class Manufacturer < ActiveRecord::Base
 has_many :products
 has_many :transporters, :through => :products
end

class Product < ActiveRecord::Base
 belongs_to :manufacturer
 belongs_to :transporter
end

class Transporter < ActiveRecord::Base
 has_many :products
 has_many :manufacturers, :through => :products
end

All four user types will be able to login, but they will have different permissions and views, etc. I don't think I can put them in the same table (Users), however, because they will have different requirements, ie: vendors and manufacturers must have a billing address and contact info (through validations), but admins and employees should not have these fields.

If possible, I would like to have a single login screen as opposed to 4 different screens.

I'm not asking for the exact code to build this, but I'm having trouble determining the best way to make it happen. Any ideas would be greatly appreciated - thanks!

like image 519
aguynamedloren Avatar asked Dec 29 '10 04:12

aguynamedloren


1 Answers

Your basic approach seems reasonable. I would advise you to make a base class of User and use STI for specific User types, for instance:

class User < ActiveRecord::Base
end

class Manufacturer < User
 has_many :products
 has_many :transporters, :through => :products
end

...etc. This way if there's ever the need to aggregate multiple user types into one relationship regardless of type, you have one table to describe Users in general. This is a fairly common approach.

Depending on how much access different users will have to the system, you may want to look at a Role Management gem like Declarative Authorization.

like image 116
Dave Sims Avatar answered Oct 01 '22 22:10

Dave Sims