How to model system with different types of users?

2019-07-07 03:06发布

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

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?

2条回答
Emotional °昔
2楼-- · 2019-07-07 03:55

I would strongly advise using Devise for authentication, CanCan to manage your permissions and something like Rolify or Role Model to define distinct roles for your different types of users.

I've written up a tutorial to get started with these here: http://www.phase2technology.com/blog/authentication-permissions-and-roles-in-rails-with-devise-cancan-and-role-model/

查看更多
Evening l夕情丶
3楼-- · 2019-07-07 03:56

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

This allows you to ask something like user.franchisor? || user.manager? whenever you need different permissions.

This is simple and a good point to start. As long as it does not get more complex I would avoid using complex gems.

查看更多
登录 后发表回答