ruby-on-rails-3 - 将 cancan 应用于自定义 Action

标签 ruby-on-rails-3 cancan

我正在开发一个投票应用程序,并使用 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_userPoll,但在您使用的 Controller 中:show_useruser - 您需要使用 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/

相关文章:

ruby-on-rails - 避免在 meta_search 中选择 * 查询

jquery - 如何使用rails 3在jQuery ajax成功方法上渲染部分

ruby-on-rails - 使用 CanCan,我如何根据关联/子属性限制能力

ruby-on-rails - 让用户使用 CanCan 和 Devise 更新自己的帖子

ruby-on-rails - 自定义助手的范围

ruby-on-rails-3 - 通过模型关系使用 CanCan 授权操作

ruby-on-rails - 如果条件在每个做 Rails

ruby-on-rails-4 - ActiveModel::ForbiddenAttributesError + cancan + rails 4 + 带作用域 Controller 的模型

jquery - 如何显示未经授权的可以访问的错误

ruby-on-rails - 设计限制注册到管理员