【发布时间】:2021-03-09 01:20:01
【问题描述】:
我正在使用 rolify cancan 并使用 ROR 设计 gem。我目前正在尝试添加 3 种类型的角色管理员、雇主和雇员。当我执行以下命令时:
user = User.find(1)
user.add_role("employee")
角色被创建并添加,但是如果我对一个新用户重复这些步骤,它会创建一个具有新角色的第二个用户。不应该使用同一个角色吗?
代码如下: 用户.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
rolify
extend Devise::Models
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :fullname, presence: true
has_many :posts
has_many :applications
has_many :users, through: :applications
has_one_attached :image
has_many :employee_reviews, class_name: "EmployeeReview", foreign_key: "employee_id"
has_many :employer_reviews, class_name: "EmployerReview", foreign_key: "employer_id"
def employer?
has_role?(:employer)
end
def employee?
has_role?(:employee)
end
end
角色.rb
class Role < ApplicationRecord
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource,
:polymorphic => true,
:optional => true
validates :resource_type,
:inclusion => { :in => Rolify.resource_types },
:allow_nil => true
scopify
end
【问题讨论】:
-
我觉得你必须创建一个记录,然后才能为其添加角色。相反,您将获得 resource_type = NULL 的角色,就像在您的屏幕截图中一样
标签: ruby-on-rails cancancan rolify