声明不同用户角色的最佳实践?

use*_*086 5 ruby activerecord ruby-on-rails

我想在我的网站上声明不同的用户角色,我想知道在 Rails 中执行此操作的最佳实践是什么?现在我有两个选择:

选项1:

我创建表 Users 并声明一个字符串列,我可以在其中存储用户角色的名称(超级管理员、管理员、教练、玩家)

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
Run Code Online (Sandbox Code Playgroud)

在 User 类中,我保存这样的值:

class User < ActiveRecord::Base
  ROLES = %w[SuperAdmin, Admin, Player, Coach]
end
Run Code Online (Sandbox Code Playgroud)

选项 2:

我仅为角色创建一个单独的表。在 Users 表中,我有用于存储 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
Run Code Online (Sandbox Code Playgroud)

如果从搜索速度、新角色的添加以及未来的维护等方面考虑,什么是更好的选择?

mar*_*nja 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
Run Code Online (Sandbox Code Playgroud)

原因如下:您不需要has_many角色,因为您无法将相同的角色与不同的用户关联。这是典型的HABTM关系。是的,稍后它可能会成为性能问题,因为为每个用户获取具有关联记录的所有角色可能非常困难。然后,您将研究其他变体进行优化:位图、密集缓存或其他。

希望你觉得它有用。