Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and forms: drop down with range of numbers and Unlimited

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?

like image 808
Hommer Smith Avatar asked Apr 06 '12 04:04

Hommer Smith


2 Answers

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.

like image 199
Michael Slade Avatar answered Sep 21 '22 03:09

Michael Slade


If I understand the question correctly, you can use options_for_select and prompt to do this a little more cleanly than what is shown in the selected answer:

<%= f.select :credit, options_for_select(0..500), { prompt: "No Limit" } %>

See the docs here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

like image 43
Javid Jamae Avatar answered Sep 24 '22 03:09

Javid Jamae