How do I pass the Hash to Grape method to the API?
I'm having problems with gem Grape and parameter validation. The idea is to create a complex object using nested attributes through an API service.
I have a way to create a trip, I have many directions, and I want to pass to the destination using a hash (using a helper accepts_nested_attributes_for
).
I have this grape limit by parameter:
requires :destinations, type: Hash
And I'm trying to send something like this:
{ destinations => [
{ destination: { name => 'dest1'} },
{ destination: { name => 'dest2'} },
{ destination: { name => 'dest3'} }
]}
To create something like the structure below inside the method and get the ride created:
{ trip: {
name: 'Trip1', destinations_attributes: [
{ name: 'dest1' },
{ name: 'dest2' },
{ name: 'dest3' }
]
}}
I am using chrome extension for POSTMAN to call an API method.
Here's a screen capture done:
If anyone can help me I would be very grateful.
source to share
For reasons of what you are trying to send, you need to change the Grape constraint, because destinations
- this is Array
, not Hash
:
requires :destinations, type: Array
When sending a request, you don't need a hash of the recipient:
{ destinations => [
{ name => 'dest1', other_attribute: 'value', etc... },
{ name => 'dest2', other_attribute: 'value', etc... },
{ name => 'dest3', other_attribute: 'value', etc... }
]}
This creates an array of hashes.
To send this via POSTMAN, you need to change this destinations
send parameter and add some lines to POSTMAN. Something like:
destinations[][name] 'dest1'
destinations[][other_attribute] 'value1'
destinations[][name] 'dest2'
destinations[][other_attribute] 'value2'
destinations[][name] 'dest3'
destinations[][other_attribute] 'value3'
Hope this answers your questions. Let me know if this is what you were looking for.
source to share