Spance Spance - 7 months ago 58
Ruby Question

Rails for loop with select helper

I have this form:

<%= form_for @score do |f| %>
<%= f.hidden_field :site_id %>
<%= f.select(:value, [['1', 1], ['2', 2], ['3', 3], ['4', 4]]) %>
<%= f.submit "Submit" %>
<% end %>


And I want to have the select values go all the way up to 10, but I don't want to manually but them in there. I'm wondering if there is a way to DRY that line up? Or will have I have to manually put 10 elements inside that array?

Thanks

Answer

If they're just singular values, select can deal with that:

<%= f.select(:value, (1..10).to_a) %>

If you care about having string/number pairs:

<%= f.select(:value, (1..10).collect {|n| [ n.to_s, n ] }) %>