Rails: select form from array / list of instance variables

I have a rails application where in the form I have a form selection (drop down list). For example, a user may select one of 1,2,3,4,5

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

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

How can I just put the array in the form selector helper and not list each element 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> 
+4
source share
1 answer

this should work:

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

some explanation:

form select can handle both hash-like and massive options. 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 ] } @formlist.map { |value| [ value, value ] } does the last

+13
source

Source: https://habr.com/ru/post/1447248/


All Articles