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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With