Rails 和表格:下拉数字范围和无限 [英] Rails and forms: drop down with range of numbers and Unlimited

查看:23
本文介绍了Rails 和表格:下拉数字范围和无限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有这个:

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

这将导致:

<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>
...

我如何在该选择中添加另一个选项,即All"并且哪个值应该是nil?

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

推荐答案

这将几乎做你想做的:

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

select 可以为选项列表采用多种格式.其中之一是数组数组,如here给出.外部数组中的每个元素都是一个 2 元素数组,依次包含显示的选项文本和表单值.

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.

上面的map(0..500) 变成这样的数组,其中显示的选项与表单值相同.然后添加最后一个选项.

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.

请注意,如果选择Unlimited",这将为参数生成值"(空字符串) - 如果您将选择字段放入表单并提交表单,浏览器将发送 用于该表单参数,并且无法将 nil 作为表单参数显式发送.如果您真的想要,您可以使用一些巧妙的 javascript 让浏览器根本不发送参数,但这比简单地添加要多得多:

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

到您的控制器操作.

这篇关于Rails 和表格:下拉数字范围和无限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆