Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing Json-Api with Rails Strong Parameters

Tags:

I am using Active Model Serializers 0.10.x with EmberCLI and Rails while trying to have the Json-Api as the Adapter. GET requests are working, but deserialization for the Active Model is not even though I tried to implement the rails strong_parameters solution described by jimbeaudoin here.

My latest attempt in saving a comment:

Payload:

{"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"}} 

Console Output:

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

Comments Controller:

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 

Noting that if I set the parameters to only params.permit(...), the server saves it with everything null (I did not set any constraints on the comments model for now):

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" 

You can access the full code here.

like image 478
Deovandski Avatar asked Sep 10 '15 00:09

Deovandski


2 Answers

Update #2: For AMS >= 0.10.2, please check other answers.

Update #1: Answer is still valid for AMS 0.10.1.

If you use 0.10.0.rc4, you can now use the Deserialization implementation described on 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 

Bonus: If you use Ember Data, then you can see an example implementation on my Fakktion Github repo.

like image 145
Deovandski Avatar answered Sep 18 '22 15:09

Deovandski


For AMS >= 0.10.2

In 0.10.2 there was a cleanup so after 0.10.2 use:

def post_params    ActiveModelSerializers::Deserialization.jsonapi_parse(params) end 

Reference: https://github.com/rails-api/active_model_serializers/commit/252f9c4ae932e6280dfe68605d495b208fe22ba7

like image 22
rolkos Avatar answered Sep 19 '22 15:09

rolkos