Reputation: 5410
I need to create a select box that goes from 1 to a number defined in a active record. This number will change.
So far I know I can create a select box like this:
<%= f.select :numbers, %w[1 2 3 4 5 6 7 8 9 10 ] %>
but what I need is something like this:
<%= f.select :numbers, %w[[email protected]] %>
is there a way to create a nice dynamic select box in rails or do I need to manually create select tags in html with a for loop or something like that?
Thanks
Upvotes: 0
Views: 946
Reputation: 434585
You can turn a Range into an Array using the to_a
method:
<%= f.select :numbers, (1 .. @user.number).to_a %>
Or you can hand f.select
the raw range and it will call to_a
for you:
<%= f.select :numbers, 1 .. @user.number %>
From the fine manual:
select(object, method, choices, options = {}, html_options = {})
Create a select tag and a series of contained option tags for the provided object and method. The option currently held by the object will be selected, provided that the object is available.
There are two possible formats for the choices parameter, corresponding to other helpers’ output:
- A flat collection: see
options_for_select
- A nested collection: see
grouped_options_for_select
options_for_select(container, selected = nil)
Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
A Range is an Enumerable so both f.select
calls above should yield the same result.
Upvotes: 1