【发布时间】:2021-02-19 09:52:38
【问题描述】:
我的控制器看起来像这样:
class RecipesController < ApplicationController
skip_before_action :authenticate_user!, only: [:index, :show]
def index
if params[:query].present?
@recipes = policy_scope(Recipe).search_by_title_and_description(params[:query]).order(created_at: :desc)
else
@recipes = policy_scope(Recipe).order(created_at: :desc)
end
end
def show
@recipe = Recipe.find(params[:id])
@recipes = Recipe.first(5)
end
end
我的政策.rb:
class RecipePolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
def index?
false
end
def show?
false
end
end
end
这是将“授权@recipe”添加到显示操作时的错误消息: 我需要 Pundit 对每个配方的 cmets 的授权,而不是配方展示动作本身的授权。我做错了什么?感谢您的帮助!!
【问题讨论】:
-
您的
show?方法已硬编码false。因此,在任何情况下都不允许用户查看任何配方。我建议阅读 Pundit 文档中的 how to define policy rules。有一些很好的例子。 -
@spickermann 是否通过编写 - def show 在 policy.rb 中硬编码?假结束 - ?
-
是的,当
show?方法返回false时,这意味着当前用户无权查看当前recipe。您需要将false替换为在您的应用程序上下文中有意义的代码,并且当当前用户被允许查看特定配方时返回true(仅)。
标签: ruby-on-rails ruby rubygems pundit