如何用Rails强参数反序列化json-api?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)

我最近试图保存一条评论:

有效载荷:

{"data":{
   "attributes": {"soft_delete":false,"soft_delete_date":null,"text":"hjfgfhjghjg","hidden":false,"empathy_level":0},
   "relationships":{
     "user":{"data":{"type":"users","id":"1"}},
     "post":{"data":{"type":"posts","id":"1"}}},"type":"comments"}}

控制台输出:

Completed 400 Bad Request in 13ms (ActiveRecord: 8.6ms)
ActionController::ParameterMissing (param is missing or the value is empty: data):

财务主任:

class Api::V1::CommentsController < MasterApiController
    respond_to :json
    ...
    def create
        render json: Comment.create(comment_params)
    end
    ...
    def comment_params
        #Deserialization issues... Waiting for #950 https://github.com/rails-api/active_model_serializers/pull/950
        params.require(:data).require(:attributes).permit(:text, :user_id, :post_id, :empathy_level, :soft_delete_date, :soft_delete, :hidden)
    end
end

注意,如果我将参数设置为许可证(.),服务器将其保存为空(我目前没有对注释模型设置任何约束):

data: {id: "9", type: "comments",…}
attributes: {soft_delete: null, soft_delete_date: null, text: null, hidden: null, empathy_level: null}
id: "9"
relationships: {post: {data: null}, user: {data: null}}
type: "comments"

您可以访问完整的代码:这里

提问于
用户回答回答于

def post_params
    ActiveModel::Serializer::Adapter::JsonApi::Deserialization.parse(params.to_h) 
    // or (params.to_unsafe_h) in some cases like in my example below...
end

用户回答回答于

扫码关注云+社区