Rails:表单从数组/列表实例变量中选择

时间:2022-09-26 20:26:17

I have a rails app where in a form, I have a form select (drop down list). For example the user can select from 1,2,3,4,5

我有一个rails应用程序,在表单中,我有一个表单选择(下拉列表)。例如,用户可以从1,2,3,4,5中进行选择

Say for example I had these values stored in an array as an instance variable like:

比方说,我将这些值存储在数组中作为实例变量,如:

@formlist = [1,2,3,4,5]

@formlist = [1,2,3,4,5]

How can I simply put the array into the form select helper rather than listing each item separately. At the moment my code is:

我怎样才能简单地将数组放入表单选择助手中,而不是单独列出每个项目。目前我的代码是:

<tr>
  <th><%= f.label(:heat_level, "Heat Level") %></th>
  <td><%= f.select(:heat_level,{ 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5"}) %></td>
</tr>

1 个解决方案

#1


14  

this should work:

这应该工作:

f.select(:heat_level, @formlist.map { |value| [ value, value ] })

some explanation:

一些解释:

form select can handle both hash-like and array-like options list. Meaning, both { 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5"}

表单选择可以处理类似哈希和类似数组的选项列表。含义,{1 =>“1”,2 =>“2”,3 =>“3”,4 =>“4”,5 =>“5”}

and

[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]

[[1,1],[2,2],[3,3],[4,4],[5,5]]

will work.

将工作。

@formlist.map { |value| [ value, value ] } does the latter

@ formlist.map {| value | [value,value]}做后者

#1


14  

this should work:

这应该工作:

f.select(:heat_level, @formlist.map { |value| [ value, value ] })

some explanation:

一些解释:

form select can handle both hash-like and array-like options list. Meaning, both { 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5"}

表单选择可以处理类似哈希和类似数组的选项列表。含义,{1 =>“1”,2 =>“2”,3 =>“3”,4 =>“4”,5 =>“5”}

and

[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]

[[1,1],[2,2],[3,3],[4,4],[5,5]]

will work.

将工作。

@formlist.map { |value| [ value, value ] } does the latter

@ formlist.map {| value | [value,value]}做后者