如何通过curl发布数组值?

时间:2022-07-01 12:32:49

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

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

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

The JSON response:

JSON响应:

{
  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:

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

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?

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

1 个解决方案

#1


16  

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

#1


16  

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