【问题标题】:Rolify Gem: User has to have at least one roleRolify Gem:用户必须至少拥有一个角色
【发布时间】:2019-06-17 15:56:29
【问题描述】:

如何使用 rolify gem 验证用户是否存在至少一个角色?我尝试按照下面的方法验证 User.rb 中角色的存在,但它不起作用。

奖励:是否可以不允许管理员用户取消自己的管理员角色?

用户.rb:

class User < ApplicationRecord
  rolify
  validates :roles, presence: true
end

编辑表格:

  = form_for @user do |f|
    - Role.all.each do |role|
      = check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id)
      = role.name
    = f.submit

控制器:

class UsersController < ApplicationController
  before_action :set_user, only: [:edit, :update, :destroy]

  def edit
    authorize @user
  end

  def update
    authorize @user
    if @user.update(user_params)
      redirect_to users_path
    else
      render :edit
    end
  end

  private
  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit({role_ids: []})
  end
end

当用户有 1 个以上的角色时,它可以正常工作,但如果我删除所有角色,它会报错:

【问题讨论】:

  • Rack 会自动删除没有任何值的任何参数。因此,如果您提交与{ users: {}} 等效的内容,它将删除users 键,这将导致.require 引发错误。
  • 您可以改用= f.collection_checkboxes :role_ids, Role.all, :id, :name,这将创建一个可以正常工作的复选框列表。
  • @max - 谢谢。 collection_check_boxes 比我以前的效果更好!

标签: ruby-on-rails rolify


【解决方案1】:

您可以创建自定义验证以要求用户至少具有一个角色:

class User < ActiveRecord::Base
  rolify
  validate :must_have_a_role

  private
  def must_have_a_role
    errors.add(:roles, "must have at least one") unless roles.any?
  end
end 

存在验证实际上仅适用于属性而不是 m2m 关联。

是否可以不允许管理员用户取消自己的管理员角色?

这是可能的,但会相当复杂,因为 Rolify 使用 has_and_belongs_to_many 关联,而不是 has_many through:,它可以让您使用关联回调。

【讨论】:

  • 有效!同样,我必须在表单中添加= f.error :roles, class: 'text-danger',才能显示错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2015-08-01
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多