[英]How to populate a dropdown in rails using a loop?
I would like to populate a dropdown in Rails dynamically using a loop. 我想使用循环动态填充Rails中的下拉列表。 I want to display the number of days 1 to 30 in the dropdown.
我想在下拉列表中显示1到30天的天数。 I tried this but it printed the
select
box multiple times on my html page. 我尝试了这个但是它在我的html页面上多次打印了
select
框。
<%
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: 在select语句中执行此循环:
(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. 它应该按照您期望的方式创建选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.