我正在使用Devise进行身份验证,Rolify进行角色管理,以及Cancan 2.0进行授权。
我想允许:admin角色更改用户的角色,但禁止其他所有用户访问。
以下是我尝试过但未成功的方法:
#ability.rb
class Ability
include CanCan::Ability
def initialize(user)
if user.has_role? :admin
can :access, :all
elsif user.has_role? :moderator
can [:index, :read, :update, :destroy], :users, :user_id => user.id
cannot :access, :users, [:role_ids]
end
end
#application_controller.rb
...
rescue_from CanCan::Unauthorized do |exception|
redirect_to root_url, :alert => exception.message
end
我故意在用户表单中保留了关联:
#_form.html.erb
<%= simple_form_for @user do |f| %>
<%= f.association :roles, as: :check_boxes %>
<%#= f.association :roles, as: :check_boxes if can? :update, @user, :roles %>
<%= f.button :submit %>
<% end %>
控制器
#users_controller.rb
class UsersController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def index
@users = User.accessible_by(current_ability)
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.update_without_password(params[:user])
if successfully_updated
redirect_to @user
else
render :action => "edit"
end
end
end
以及这个模型:
#user.rb
class User < ActiveRecord::Base
rolify
attr_accessible :role_ids
...
现在,如果具有:moderator角色的用户尝试更改另一个用户(或自己)的角色,那么将发生以下情况:
- 抛出CanCan::Unauthorized异常并将用户重定向到root_url
- 用户的角色将被更改
我尝试在users_controller.rb中根据用户角色操作查询参数。如果我在def update之后放置一个日志记录语句,则输出如下:
2013-04-24 12:42:21 [4161] DEBUG (0.1ms) BEGIN
2013-04-24 12:42:21 [4161] DEBUG (0.3ms) INSERT INTO "users_roles" ("user_id", "role_id") VALUES (5, 1)
2013-04-24 12:42:21 [4161] DEBUG (0.4ms) COMMIT
2013-04-24 12:42:21 [4161] DEBUG User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "5"]]
2013-04-24 12:42:21 [4161] DEBUG {"username"=>"Blabla", "email"=>"bla@bla.com", "password"=>"", "password_confirmation"=>"", "approved"=>"1", "role_ids"=>["1", "2", ""]}
我一定是忽略了什么...
cannot :access, :users, [:role_ids]
能力规则是什么意思?它似乎要么是语法错误,要么是我漏掉了什么。 - zkcro