Rails and forms: drop down with range of numbers a

2019-02-22 22:52发布

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?

2条回答
戒情不戒烟
2楼-- · 2019-02-22 23:31

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

查看更多
女痞
3楼-- · 2019-02-22 23:38

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.

查看更多
登录 后发表回答