提交课程名册.一次添加3名学生.每个学生都有第一个,最后一个,年龄.
问题:我们怎样才能让所有学生都在阵列中?
students[0] => Array ( ["first"] => "first name for 0",["last"] => "last name for 0",["age"] => "age for 0" ),students[1] => Array ( ["first"] => "first name for 1",["last"] => "last name for 1",["age"] => "age for 1" ),...@H_404_5@细节
对于一个学生:<input type="text" name="first"> <input type="text" name="last"> <input type="text" name="age">@H_404_5@我们可以在单独的数组中返回多个学生:
<input type="text" name="students[first][]"> <input type="text" name="students[last][]"> <input type="text" name="students[age][]">@H_404_5@它返回了一系列的第一,持续和年龄
students["first"] = [array of first names] students["last"] = [array of last names] students["age"] = [array of ages]@H_404_5@从理论上讲,我们可以通过访问相同的索引来获取学生的所有信息(对每个数组说“3”).
我们不希望以编程方式在表单中添加索引.
不要:<input type="text" name="students[hardcoded_index][first]"> <input type="text" name="students[hardcoded_index][last]"> <input type="text" name="students[hardcoded_index][age]">@H_404_5@如果由于任何原因它很重要,我们使用Rails进行视图,但可以使用表单助手或HTML.
解决方法
tl; dr:在学生输入名称后添加空括号([]).
摆弄Rack::Utils.parse_nested_query似乎你可以得到你想要的有效载荷:
<!-- first student --> <input type="text" name="students[][first]"> <input type="text" name="students[][last]"> <input type="text" name="students[][age]"> <!-- second student --> <input type="text" name="students[][first]"> <input type="text" name="students[][last]"> <input type="text" name="students[][age]">@H_404_5@注意学生之后的空括号([]).这告诉Rack你希望学生param成为一个数组.遇到的后续参数(具有相同名称)将启动一个新元素.
POST / myroute?students [] [first] = foo& students [] [last] = bar& students [] [age] = 21& students [] [first] = baz& students [] [last] = qux& students [] [年龄] = 19
获取解析如下:
{"students" => [ { "first" => "foo","last" => "bar","age" => "21" },{ "first" => "baz","last" => "qux","age" => "19" } ]}@H_404_5@进一步阅读:http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query