Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Form Select From Array/List Instance Variable

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

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

@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>
like image 533
Muhammed Bhikha Avatar asked Nov 20 '12 14:11

Muhammed Bhikha


1 Answers

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"}

and

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

will work.

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

like image 149
Vlad Khomich Avatar answered Nov 22 '22 13:11

Vlad Khomich