Pundit部分的This部分说,我们可以控制哪些属性被授权更新。但在使用active_model_seriallizers gem的情况下会失败:
def post_params
# originally geneated by scaffold
#params.require(:post).permit(:title, :body, :user_id)
#To deserialize with active_model_serializers
ActiveModelSerializers::Deserialization.jsonapi_parse!(
params,
only: [:title, :body, :user]
)
end如果我按照Pundit的建议修改PostsController update操作:
def update
if @post.update(permitted_attributes(@post))
render jsonapi: @post
else
render jsonapi: @post.errors, status: :unprocessable_entity
end
end它会失败,并显示错误:
ActionController::ParameterMissing (param is missing or the value is empty: post):
app/controllers/posts_controller.rb:29:in `update'我还按如下方式创建了PostPolicy:
class PostPolicy < ApplicationPolicy
def permitted_attributes
if user.admin? || user.national?
[:title, :body]
else
[:body]
end
end
end但它对上述错误没有影响。
你知道我们该怎么做吗?
发布于 2019-10-28 16:41:39
我得到的解决方案(感谢@max提供了一些技巧和技巧)如下:
在config/application.rb中添加以下行:
config.action_controller.action_on_unpermitted_parameters = :raiserescue_from添加到AplicationController或您确切感兴趣的位置:class ApplicationController < ActionController::API
include ActionController::MimeResponds
include Pundit
rescue_from Pundit::NotAuthorizedError, ActionController::UnpermittedParameters, with: :user_not_authorized
...
private
def user_not_authorized
render jsonapi: errors_response, status: :unathorized
end
def errors_response
{
errors:
[
{ message: 'You are not authorized to perform this action.' }
]
}
end
end然后将pundit_params_for方法添加到PostsController并更改update操作(在我的示例中,我只想限制update操作中的一些属性:)
class PostsController < ApplicationController
...
def update
if @post.update(permitted_attributes(@post))
render jsonapi: @post
else
render jsonapi: @post.errors, status: :unprocessable_entity
end
end
private
def post_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(
params,
only: [:title, :body, :user]
)
end
def pundit_params_for(_record)
params.fetch(:data, {}).fetch(:attributes, {})
end
end瞧啊。现在,如果不允许的属性将被提交用于update操作,响应将具有500状态并包含ApplicationController#errors_response method中指定的错误。
ATTENTION:如果您在请求中发布了一些关系(例如,您可以将Author作为belongs_to关系与Post一起发布),它仍然会失败。像以前一样使用pundit_params_for将无法提取相应的author_id值。要了解该方法,请参阅我的another帖子,其中我解释了如何使用它。
希望这能有所帮助。
https://stackoverflow.com/questions/58559549
复制相似问题