ruby-on-rails - 声明不同用户角色的最佳实践?

标签 ruby-on-rails ruby activerecord

我想在我的站点上声明不同的用户角色,我想知道在 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/

相关文章:

ruby-on-rails - 让 Rails 5 应用程序返回 JSON API 格式

ruby-on-rails - ruby rails : is it okay to use old school database access without migrations?

ruby - Ruby 中的三重单引号与三重双引号

ruby-on-rails - 没有收到来自 ExceptionNotifier 的电子邮件

ruby-on-rails - Rake任务rails :upgrade:check is not working on windows. Rails 3升级问题

ruby-on-rails - rails : Concat Two CollectionProxies with two different models

php - Yii2 ActiveRecord 与关系结果转换为 JSON

ruby-on-rails - Web 服务上的 Rails 授权

ruby-on-rails - 默认情况下是否可以从我的 Rails 应用程序中删除 public/index.html?

ruby-on-rails - Rails + PostgreSQL : How to get products that have been ordered at least once + get the order # and the manager id