如何仅允许管理员可以在用户表中使用Cancancan更新角色列



我想让管理员可以通过数据库中的"编辑角色"列将其他用户设置为admin/Manager。我尝试使用坎坎坎宝石来做到这一点,但什么也没发生。

我该怎么做?

能力.rb

def initialize(user)
  user ||= User.new 
  if user.admin?
    can [:create, :update, :destroy], [Organization, Club, User]
  elsif user.manager?
    can [:create, :update, :destroy], [User, Event, News, User_club, User_event]
    can :update, Club
    can :read, :all
    cannot :update, user.role
  else
    can :read, :all
    can :create, User
    can :update, User, user_id: user.id
    cannot :update, user.role
  end
end

edit.html.erb

<% if can? :update, @user.role %>
   <%= f.label :role %>
   <%= f.number_field :role, class: "form-control" %>
<% end %>

您尝试此

class Ability
  include CanCan::Ability
  def initialize(user)
    can :read, :all                   # allow everyone to read everything
    if user && user.admin?
      can :access, :rails_admin       # only allow admin users to access Rails Admin
      can :dashboard                  # allow access to dashboard
      if user.role? :superadmin
        can :manage, :all             # allow superadmins to do anything
      elsif user.role? :manager
        can :manage, [User, Product]  # allow managers to do anything to products and users
      elsif user.role? :sales
        can :update, Product, :hidden => false  # allow sales to only update visible products
      end
    end
  end
end

最新更新