【发布时间】:2016-03-22 16:27:39
【问题描述】:
提交班级名册。一次添加 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"
),
...
详情
对于一名学生:
<input type="text" name="first">
<input type="text" name="last">
<input type="text" name="age">
我们可以像这样在单独的数组中返回多个学生:
<input type="text" name="students[first][]">
<input type="text" name="students[last][]">
<input type="text" name="students[age][]">
它返回一个由第一个、最后一个和年龄组成的数组
students["first"] = [array of first names]
students["last"] = [array of last names]
students["age"] = [array of ages]
理论上,我们可以通过访问相同的索引(比如每个数组为“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]">
如果出于任何原因很重要,我们将 Rails 用于视图,但可以使用表单助手或 HTML。
【问题讨论】:
标签: html arrays forms ruby-on-rails-4