Ruby-on-rails – Rails and forms: drop down with range of numbers and Unlimited

drop-down-menuformsruby-on-rails

I have this right now:

<%= f.select :credit, (0..500) %>

This will result in this:

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
...

How would I add another option in that select that would be "All" and which value should be nil?

Best Answer

This will almost do what you want:

<%= f.select :credit, ((0..500).map {|i| [i,i] } << ["No limit",nil]) %>

select can take a number of formats for the list of options. One of them is an array of arrays, as given here. Each element in the outer array is a 2-element array, containing the displayed option text and the form value, in that order.

The map above turns (0..500) into an array like this, where the option displayed is identical to the form value. Then one last option is added.

Note that this will produce a value of "" (an empty string) for the parameter if "Unlimited" is selected - if you put a select field into a form and the form is submitted, the browser will send something for that form parameter, and there is no way to send nil as a form parameter explicitly. If you really wanted to you could use some clever javascript to get the browser to not send the parmeter at all, but that would be more work than simply adding:

param[:credit] == "" and param[:credit] = nil

to your controller action.