我正在开发一个投票应用程序,并使用 Devise 和 Cancan 进行身份验证和授权。我有一个由 Devise 生成的用户模型和一个民意调查模型。民意调查属于用户。我的问题是我的民意调查 Controller 中有一个自定义操作,但我无法让 Cancan 使用该自定义操作。这就是我在代码中尝试做的事情:
配置/routes.rb:
match 'users/:user_id/polls' => 'polls#show_user'
能力.rb:
def initialize(user)
user ||= User.new
if user.is? :admin
can :manage, :all
else # default
can :read, :all
can :manage, Poll, :user_id => user.id
can :show_user, Poll, :user_id => user.id
end # if else admin
end
polls_controller.rb:
class PollsController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource :except => :show_user
def show_user
authorize! :show_user, user
@polls = Poll.find_all_by_user_id(params[:user_id])
render "index"
end
<...>
end
这个想法是,只有当投票所有者登录时才能查看用户的投票。但是,使用此代码,当投票所有者登录时,该用户会被踢出该页面,并显示一条消息:说授权失败。如果我删除行 authorize! :show_user, user
,则登录的用户可以查看所有其他用户的投票(授权根本不起作用)。
有人能看到我可能缺少什么吗?提前致谢!
最佳答案
在 abiltity.rb
中,您的动词/名词组合是 :show_user
和 Poll
,但在您使用的 Controller 中:show_user
和 user
- 您需要使用 Poll
来代替。
如果您希望允许用户查看他们自己的所有民意调查
,您可以采用如下方式:
能力.rb
:
can :show_polls_for, User, :id => user.id
polls_controller.rb
:
def show_user
authorize! :show_polls_for, user
...
end
关于ruby-on-rails-3 - 将 cancan 应用于自定义 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13539458/