Ruby on rails 专家-政策不被认可
我正在实现pundit,希望将用户#编辑和用户#更新操作仅限于当前用户Ruby on rails 专家-政策不被认可,ruby-on-rails,pundit,Ruby On Rails,Pundit,我正在实现pundit,希望将用户#编辑和用户#更新操作仅限于当前用户 def edit @user = current_user authorize(@user) end def update @user = current_user authorise(@user) if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to edit_us
def edit
@user = current_user
authorize(@user)
end
def update
@user = current_user
authorise(@user)
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to edit_user_path
else
render 'edit'
end
end
以下是我尝试的策略,(a)不起作用,(b)不合逻辑
class UserPolicy
attr_reader :user, :user
def initialise(user, user)
@user = user
end
def update?
true
end
alias_method :edit?, :update?
end
我现在更新了我的用户策略,如下所示。我已将测试操作设置为false,因为所有操作均已授权:
class UserPolicy < ApplicationPolicy
def new?
create?
end
def create?
false
end
def edit?
update?
end
def update?
false
#user.id == record.id
end
end
当我现在导航到我的用户#编辑操作时,我收到:
Pundit::AuthorizationNotPerformedError
首先,确保你有 您的应用程序/app/controllers/application\u controller.rb 然后,在您的
UserPolicy
您的应用程序/应用程序/策略/章节_policy.rb
您必须知道,如果您没有当前用户
方法,您将需要在应用程序控制器中定义一个
非常感谢你。因此ApplicationPolicy为可以覆盖的REST操作指定了默认权限。i、 默认更新?是否为false和edit?使用更新?默认值。但是,如果当前用户是记录所有者,则这些默认值将被允许的UserPolicy覆盖?是的,您正在覆盖
UserPolicy
中的默认值update?
和edit?
(UserPolicy
继承自ApplicationPolicy
)不强制使用应用程序策略,但是,这是一个很好的做法。在您的策略中,您覆盖了您只需要的内容。我不清楚如何在ApplicationPolicy中设置记录。例如,如果我要为“new”创建一个UserPolicy,那么此时将没有用户实例,那么记录将设置为什么?您总是有一个@user
。在您的新操作中,您可以拥有@user=user.new
如果出于某种原因(不是新操作案例),您没有@user
,您可以随时调用授权您想要的对象:\u策略\u操作\u您想要的?
Pundit::AuthorizationNotPerformedError
class ApplicationController < ActionController::Base
include Pundit
end
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
def index?
false
end
def show?
scope.where(:id => record.id).exists?
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
def scope
Pundit.policy_scope!(user, record.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
scope
end
end
class UserPolicy < ApplicationPolicy
def edit?
user.id == record.id
end
def update?
edit?
end
end
def edit
user
end
def update
if user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to edit_user_path
else
render 'edit'
end
end
private
def user
@user ||= User.find(params[:id])
end