16

I like to test an API backend which is designed as shown in the following example:

http://localhost:3000/api/v1/shops/1.json

The JSON response:

{
  id: 1,
  name: "Supermarket",
  products: [
    "fruit",
    "eggs"
  ]
}

Here is the corresponding model:

# app/models/shop.rb
class Shop < ActiveRecord::Base
  extend Enumerize
  attr_accessible :name, :products

  serialize :products, Array
  enumerize :products, in: %w{fruit meat eggs}, multiple: true

  resourcify

  validates :name, presence: true, length: { in: 5..50 }    
  validates :products, presence: true
end

I want to use curl to test creating and updating a entry. Therefore, I use the following commands:

Create:

$ curl -X POST http://localhost:3000/api/v1/shops.json -d \
  "shop[name]=Supermarket&shop[products]=fruit,eggs&auth_token=a1b2c3d4"

Update:

$ curl -X PUT http://localhost:3000/api/v1/shops/1.json -d \
  "shop[name]=Supermarket&&shop[products]=fruit,eggs&auth_token=a1b2c3d4"

The value for products need to be submitted as an array. When I run the above commands the following message is returned:

{"errors":{"products":["is invalid"]}

How do I need to write the values of the products array so it works with curl?

1 Answer 1

18
$ curl -X POST http://localhost:3000/api/v1/shops.json -d \
  "shop[name]=Supermarket \
  &shop[products][]=fruit \
  &shop[products][]=eggs \
  &auth_token=a1b2c3d4"
Sign up to request clarification or add additional context in comments.

3 Comments

What if I have an existing array I want to add to? Would this clear the product array and replace it with these two products? Or would it append them to the list of existing products? (I'd like to find a way to do the latter)
@TomHammond I think you should post this as a separate question, I will gladly answer you!
Sure thing - here's my question: stackoverflow.com/questions/22327098/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.