15

我喜欢测试一个 API 后端,其设计如下例所示:

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

JSON 响应:

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

这是对应的模型:

# 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

我想使用curl来测试创建和更新条目。因此,我使用以下命令:

创造:

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

更新:

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

products需要作为数组提交的值。当我运行上述命令时,将返回以下消息:

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

我如何需要编写products数组的值以便它与curl一起使用?

4

1 回答 1

17
$ curl -X POST http://localhost:3000/api/v1/shops.json -d \
  "shop[name]=Supermarket \
  &shop[products][]=fruit \
  &shop[products][]=eggs \
  &auth_token=a1b2c3d4"
于 2013-06-14T12:45:39.237 回答