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!
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.
For Multiple user systems, generally preferred ways are - use of role model or STI. If your users can have multiple roles at same time, like single user being Manufacturer and transporter, then Role base system would be good solution. If users role is fixed, then i think you should go with STI.
I suggest you make a User model, Address model, ContactInfo model, etc. You should NOT have those kinds of fields in the User model. Normalize the database. Have a FK in each of those other classes to User.id.
If you MUST keep them separate, then normalize logins and make it polymorphic to reference its owner (manufacturer, employee, etc)
精彩评论