Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept JSON through Rails API without "_attributes" for nested fields

Tags:

I've written an API with Rails and need to accept some nested_attributes in API calls.

Currently I send data via

PATCH /api/v1/vintages/1.json

{   "vintage": {     "year": 2014,     "name": "Some name",     "foo": "bar",     "sizes_attributes": [       {         "name": "large",         "quantity": "12"       },       {         "name": "medium",         "quantity": "2"       }     ]   } } 

However, I'd like to perform the following:

PATCH /api/v1/vintages/1.json

{   "vintage": {     "year": 2014,     "name": "Some name",     "foo": "bar",     "sizes": [       {         "name": "large",         "quantity": "12"       },       {         "name": "medium",         "quantity": "2"       }     ]   } } 

The difference being attributes being part of the key of the fields. I want to be able to accept_nested_attributes_for :sizes without having to use _attributes be a part of the JSON object.

Anyone know how to manage this?

like image 621
Brian Weinreich Avatar asked Dec 02 '14 23:12

Brian Weinreich


1 Answers

You are free to perform some magic in your strong parameters methods. Based on what you want, you likely have this method in your controller:

def vintage_params   params.require(:vintage).permit(:year, :name, :foo, { sizes: [:name, :quantity] }) end 

All you'd need to do is adjust the name of the sizes key in that method. I'd recommend:

def vintage_params   vintage_params = params.require(:vintage).permit(:year, :name, :foo, { sizes: [:name, :quantity] })   vintage_params[:sizes_attributes] = vintage_params.delete :sizes   vintage_params.permit! end 

This will remove the :sizes key and put it in the expected :sizes_attributes without messing up your pretty json. There is nothing you can do directly with accepts_nested_attributes_for to change the name.

like image 135
ptd Avatar answered Oct 21 '22 19:10

ptd