【发布时间】:2018-10-10 13:36:36
【问题描述】:
我不知道我是否在这里做错了,但似乎是这样。
我使用 Pundit 进行授权,我现在已经使用它设置了一些模型。
我有一个只能由管理员创建的类别模型。此外,我也不希望用户看到显示/编辑/销毁视图。我只是希望管理员可以访问它。到目前为止一切顺利。
下面会添加一些代码:
category_policy.rb
class CategoryPolicy < ApplicationPolicy
def index?
user.admin?
end
def create?
user.admin?
end
def show?
user.admin?
end
def new?
user.admin?
end
def update?
return true if user.admin?
end
def destroy?
return true if user.admin?
end
end
categories_controller.rb
class CategoriesController < ApplicationController
layout 'scaffold'
before_action :set_category, only: %i[show edit update destroy]
# GET /categories
def index
@category = Category.all
authorize @category
end
# GET /categories/1
def show
@category = Category.find(params[:id])
authorize @category
end
# GET /categories/new
def new
@category = Category.new
authorize @category
end
# GET /categories/1/edit
def edit
authorize @category
end
# POST /categories
def create
@category = Category.new(category_params)
authorize @category
if @category.save
redirect_to @category, notice: 'Category was successfully created.'
else
render :new
end
end
# PATCH/PUT /categories/1
def update
authorize @category
if @category.update(category_params)
redirect_to @category, notice: 'Category was successfully updated.'
else
render :edit
end
end
# DELETE /categories/1
def destroy
authorize @category
@category.destroy
redirect_to categories_url, notice: 'Category was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def category_params
params.require(:category).permit(:name)
end
end
application_policy.rb
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def index?
false
end
def create?
create?
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope.all
end
end
end
我的 ApplicationController 中包含 Pundit,rescue_from Pundit::NotAuthorizedError, with: :forbidden 也在那里设置。
授权本身有效,如果我使用管理员帐户登录,我可以访问 /categories/*。如果我已注销,我会收到以下信息:NoMethodError at /categories
undefined methodadmin?'对于零:NilClass`
在写这个问题时,我认为我发现了问题——我猜 Pundit 会寻找一个 nil 的用户,因为我没有登录。解决这个问题的正确方法是什么?
最好的问候
【问题讨论】:
标签: ruby-on-rails ruby pundit