我正在使用带有EmberCLI和Rails的Active Model Serializers 0.10.x,同时尝试使用Json-Api作为适配器。GET请求正在工作,但是活动模型的反序列化不起作用,尽管我尝试实现了jimbeaudoin here描述的rails strong_parameters解决方案。
我保存评论的最新尝试是:
负载:
{"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
请注意,如果我将参数设置为仅为params.permit(...),,则服务器会将其与所有内容一起保存为空(我目前没有对注释模型设置任何约束):
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"
您可以访问完整的代码here。
发布于 2016-02-22 04:36:59
更新#2:对于AMS >= 0.10.2,请检查其他答案。
更新#1:答案对于AMS 0.10.1仍然有效。
如果使用0.10.0.rc4,现在可以使用Active Model Serializers #1248中描述的反序列化实现。
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
的好处:如果你使用Ember Data,那么你可以在我的Fakktion Github repo上看到一个示例实现。
发布于 2016-09-07 22:51:51
适用于AMS >= 0.10.2的
在0.10.2中有一个清理,所以在0.10.2之后使用:
def post_params
ActiveModelSerializers::Deserialization.jsonapi_parse(params)
end
发布于 2017-02-21 15:15:06
带有AMS 0.10.2+的
使用only
哈希创建参数白名单,
def post_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(
params, only: [:title, :author, :tags]
)
end
https://stackoverflow.com/questions/32491360
复制相似问题