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

前端 未结 2 761
深忆病人
深忆病人 2021-01-18 09:39

I have this right now:

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

This will result in this:

2条回答
  •  遇见更好的自我
    2021-01-18 09:47

    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.

提交回复
热议问题