我想在我的站点上声明不同的用户角色,我想知道在 Rails 中执行此操作的最佳做法是什么?现在我有两个选择:
选项 1:
我创建表 Users 并声明一个字符串列,我可以在其中存储用户角色的名称(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
在 User 类中,我像这样保存值:
class User < ActiveRecord::Base
ROLES = %w[SuperAdmin, Admin, Player, Coach]
end
选项 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
如果我们考虑搜索速度、添加新角色和 future 维护,什么是更好的选择?
最佳答案
基本变体:
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 关系。是的,稍后它可能会成为一个性能问题,因为很难为每个用户获取所有角色和相关记录。然后您将研究其他变体以进行优化:位图、密集缓存或其他。
希望你觉得它有用。
关于ruby-on-rails - 声明不同用户角色的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763214/