Rails 通过 Curl Multipart 发送的令人困惑的结果解析数组参数 POST

Rails Baffling Result Parsing Array Param Sent Via Curl Multipart POST

请解释一下,或提供更正确的解决方案。

class Store < ApplicationRecord
  has_and_belongs_to_many :books
end

class Book < ApplicationRecord
  has_and_belongs_to_many :stores
end

我的数据库中有几本书。我想创建一个新商店,里面有几本书。

以下几个 curl 命令导致 Rails 为参数 [book_ids]:

解析一个空数组
curl -F "author[book_ids[]]=[1,2]" -F "author[description]=some description" localhost:3000/authors.multipart
    Started POST "/authors.multipart" for 127.0.0.1 at ...
    Processing by AuthorsController#create as MULTIPART
    Parameters: {"author"=>{"gesture_ids"=>[], "description"=>"some description", @headers ...

curl -F "author[book_ids[]]=\"[1,2]\"" -F "author[description]=some description" localhost:3000/authors.multipart
    Started POST "/authors.multipart" for 127.0.0.1 at ...
    Processing by AuthorsController#create as MULTIPART
    Parameters: {"author"=>{"gesture_ids"=>[], "description"=>"some description", @headers ...

curl -F "author[book_ids[]]=1" -F "author[book_ids[]]=2" -F "author[description]=some description" localhost:3000/authors.multipart
    Started POST "/authors.multipart" for 127.0.0.1 at ...
    Processing by AuthorsController#create as MULTIPART
    Parameters: {"author"=>{"gesture_ids"=>[], "description"=>"some description", @headers ...

但以下命令可以解决问题:

curl -F "author[book_ids[]=1" -F "author[book_ids[]=2" -F "author[description]=some description" localhost:3000/authors.multipart
    Started POST "/authors.multipart" for 127.0.0.1 at ...
    Processing by AuthorsController#create as MULTIPART
    Parameters: {"author"=>{"gesture_ids"=>["1","2"], "description"=>"some description", @headers ...

如您所见,该命令在几个地方缺少右括号,但它有效。检查跟踪,curl 确实为第一本书发送了以下内容。

0000: HTTP/1.1 100 Continue
=> Send data, 502 bytes (0x1f6)
0000: --------------------------538dd4bc2333141c
002c: Content-Disposition: form-data; name="store[book_ids[]"
0068: 
006a: 1
006f: --------------------------538dd4bc2333141c

author[book_ids][]=1

的正确语法

这种情况下的语法是 wrapper[key] = value(就像你描述的那样)所以对于 Array 我们声明它是值 wrapper[key][]Array 然后= 将值附加到 Array

Write now author[book_ids[]]=[1,2] 在技术上会被解析为 author: {book_ids: []} = [1,2],这显然是不正确的,解析器会忽略赋值。