Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a dropdown in rails using a loop?

I would like to populate a dropdown in Rails dynamically using a loop. I want to display the number of days 1 to 30 in the dropdown. I tried this but it printed the select box multiple times on my html page.

  <%
    for i in 0..30
  %>
      <%= select_tag "time_id", options_for_select([['Last #{i} days', i]]), class: 'form-control' %>
  <%
    end
  %>

Output:

Last #{i} days got displayed 30 times within individual select boxes.

Expected Output:

<select>
    <option name='1'>Last 1 day</option>
    <option name='2'>Last 2 days</option>
    <option name='3'>Last 3 days</option>
    ...
    ...
    <option name='30'>Last 30 days</option>
</select>
like image 727
Nital Avatar asked Sep 13 '25 22:09

Nital


1 Answers

Do this loop within the select statement:

(1..30).map { |i| ["Last #{i} #{'day'.pluralize(i)}", i] }

So remove the loop outside of the select and change your select to:

<%= select_tag "time_id", options_for_select((1..30).map { |i| ["Last #{i} #{'day'.pluralize(i)}", i] }), class: 'form-control' %>

The output of the loop will be:

[["Last 1 day", 1], ["Last 2 days", 2], ["Last 3 days", 3], etc.]

And it should create the options the way you're expecting.

like image 139
MTarantini Avatar answered Sep 15 '25 15:09

MTarantini