如何对具有不同类型用户的系统进行建模? [英] How to model system with different types of users?
问题描述
我正在开发餐厅特许经营应用.我只需要使用 User 模型并拥有安全密码.
I am working on a restaurant franchise app. I've only ever had to use a User model and has secure password.
class User < ActiveRecord::Base
has_secure_password
现在我会有不同类型的用户具有不同的访问权限和报告:
Now I would have different types of users with different access rights and reports:
franchisor user (head office)
restaurant owner / franchisee
manager
waiter
设置模型/类的推荐方法是什么?我会为每个人创建一个模型并为每个人提供 has_secure_password
还是将每个人都放入用户模型中并为其分配类型?或者做某种继承多态?
What is a recommended way to set up the models/classes?
Would I create a model for each and give each has_secure_password
or would I put everyone into the user model and assign them a type? Or do some sort of inheritance polymorphism?
推荐答案
我会在一个班级中完成,并为 User 添加一个 role
列,并为每个 User 分配一个角色.
I would do it in one class and add a role
column to User and assign a role to each User.
# in user.rb
class User < ActiveRecord::Base
has_secure_password
ROLES = %w[ franchisor restaurant_owner manager waiter ]
validates :role, :inclusion => { :in => ROLES }
ROLES.each do |role_name| # generates for each ROLE a method like this:
def #{role_name}? # def waiter?
role == '#{role_name}' # role == 'waiter'
end # end
end
这允许您询问诸如 user.franchisor?||user.manager?
每当您需要不同的权限时.
This allows you to ask something like user.franchisor? || user.manager?
whenever you need different permissions.
这很简单,也是一个很好的起点.只要它不会变得更复杂,我就会避免使用复杂的 gem.
This is simple and a good point to start. As long as it does not get more complex I would avoid using complex gems.
这篇关于如何对具有不同类型用户的系统进行建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!