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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With