【问题标题】:devise 'authorize User' results in undefined method设计“授权用户”导致未定义的方法
【发布时间】:2014-08-20 01:59:39
【问题描述】:

我从 RailsApps.org 的 Rails 4.1 Pundit / Devise 应用程序开始,并在用户控制器中调用“授权用户”时继续收到未定义的方法错误。用户可以注册、登录和编辑他们的帐户信息。单击用户链接时,结果如下:

UsersController#index 中的 NoMethodError

# 的未定义方法“授权”

这里是用户控制器...

class UsersController < ApplicationController

  before_filter :authenticate_user!
  after_action :verify_authorized

  def index
    @users = User.all
    authorize User    # <== This is the line the error occurs on
  end

  def show
    @user = User.find(params[:id])
    authorize @user
  end

  def update
    @user = User.find(params[:id])
    authorize @user
    if @user.update_attributes(secure_params)
      redirect_to users_path, :notice => "User updated."
    else
      redirect_to users_path, :alert => "Unable to update user."
    end
  end

  def destroy
    user = User.find(params[:id])
    authorize user
    user.destroy
    redirect_to users_path, :notice => "User deleted."
  end

  private

  def secure_params
    params.require(:user).permit(:role)
  end

end

还有ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

关于如何解决这个问题的任何想法?

提前致谢!

评论:这是来自 RailsApp Pundit 快速入门指南,用于解释 授权

关键字authorize 是一个辅助方法,它提供了实现实际授权的较长语句的快捷方式。我们从来没有看到完整的语句,因为我们使用了 helper 方法,但是如果我们使用它,它看起来像这样:

引发“未授权”,除非 UserPolicy.new(current_user, User).index?

authorize 辅助方法找到一个 UserPolicy 类并将其实例化,传递 current_user 对象和 User 类或 User 模型的实例,然后调用索引?方法返回真或假。您可能想知道为什么我们可以提供 User 类(如在 index 操作中)或 @user 实例变量(如在 show 操作中)。

当从控制器操作调用授权时,Pundit 会查找策略对象。我们已经看到,如果给出以下任何参数,Pundit 将找到 UserPolicy:

  • 授权用户——用户类

  • 授权@user – 一个实例变量,它是 User 类的一个实例

  • 授权用户——一个简单的变量,它是用户类的一个实例

  • 授权@users - 一组用户对象

对我来说,似乎有时会在 show 和 update 中找到辅助方法,但在 index 中却没有。

【问题讨论】:

    标签: ruby-on-rails-4 devise pundit


    【解决方案1】:

    这里似乎正在讨论这个问题:https://github.com/RailsApps/rails-devise-pundit/issues/10

    基本上,您的解决方案是: A)重新启动rails服务器,问题应该消失。每当出现问题(编辑文件等)时,您都必须这样做。 (如果有什么安慰的话,它不应该在生产中发生)

    B) 将config/intiializers/pundit.rb 中的代码移入ApplicationController(不带included do...end 块)

    【讨论】:

    • 谢谢!这终于解释了发生了什么,它又按预期工作了。
    【解决方案2】:

    User 是类名,而不是实例。还 authorize 用于创建/更新/编辑操作。对于索引,您应该use Policy

    例如UserPolicy:

    def index
      @users = UserPolicy::Scope.new(current_user, User).resolve
    end
    

    【讨论】:

    • 我在上面进行了编辑以显示相关的 RailsApp 文档并澄清似乎有时会找到辅助方法而有时却找不到。但是授权基本上按照您的指示进行,没有 ::Scope。当用户新注册并浏览链接时,用户链接有效(即索引方法)。登录的返回用户无法查看用户链接并收到未定义方法错误。
    猜你喜欢
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多