7

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>

1 Answer 1

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

Just want to update for future users, the mapping is totally unnecessary for shallow arrays f.select(:heat_level, @formlist) is gonna give you the exact same result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.