Best practice for declaring different user roles?

I want to declare different user roles on my site, and I was wondering what is the best thing to do in Rails? At the moment, I have two options:

OPTION 1:

I create a Users table and declare a single column in the row where I can store user role names (SuperAdmin, Admin, Coach, Player)

create_table "users", force: true do |t|
    t.string   "username"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "role"
end

Inside the user class, I store the values ​​as follows:

class User < ActiveRecord::Base
  ROLES = %w[SuperAdmin, Admin, Player, Coach]
end

OPTION 2:

I create a separate table for roles only. Inside the Users table, I have an integer column to hold role_id:

create_table "users", force: true do |t|
    t.string   "username"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.integer  "role_id"
end

create_table "roles", force: true do |t|
    t.string   "role_name"
end

class User < ActiveRecord::Base
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_many :users
end

What would be better if we used search speed, added new roles and future services to consideration?

+4
3

:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class CreateRolesUsersJoinTable < ActiveRecord::Migration
  def change
    create_table :roles_users, id: false do |t|
     t.integer :user_id
     t.integer :role_id
    end
  end
end

: has_many , . HABTM. , , . : , - .

, .

+2

- :)

gem cancan - , . cancan , .

0

IMO the best way is to use the standard relationship has_many belongs_tobetween the model Userand Role:

#app/models/user.rb
Class User < ActiveRecord::Base
   belongs_to :role

   before_create :set_role

   def set_role
       role = self.role_id
       role_id = "0" unless defined?(role)
   end 
end

#app/models/role.rb
Class Role < ActiveRecord::Base
   has_many :users
end

users
id | role_id | name | created_at | updated_at

roles 
id | name | created_at | updated_at

This will allow you to associate users with a specific role and continue to add / adapt roles as needed.

0
source

Source: https://habr.com/ru/post/1526798/


All Articles