轨道和形式:数字范围和无限下降 [英] Rails and forms: drop down with range of numbers and Unlimited

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

问题描述

我现在有这个:

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

如何在该选择中添加另一个选项,这将是 strong>全部,哪个值应该是 nil

解决方案

em>几乎做你想要的:

 <%= f.select:credit,((0。 .500).map {| i | [i,i]}<< [无限制,nil])%> 

选择可以采用多种格式选项列表。其中一个是阵列数组,如这里给出的。外部数组中的每个元素都是一个2元素数组,包含显示的选项文本和表单值。



map 以上的转换为$ code(0..500)到这样的数组,显示的选项与表单值相同。然后添加一个最后一个选项。



请注意,如果选择无限制,则会为参数产生一个(空字符串)的值 - 如果放置一个选择字段进入表单并提交表单,浏览器将为该表单参数发送某些,并且没有办法发送 nil 作为一个表单参数显式。如果你真的希望你可以使用一些聪明的JavaScript来让浏览器根本不发送参数,但是比直接添加更多的工作:

  param [:credit] ==和param [:credit] = nil 

到您的控制器操作。


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?

解决方案

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.

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

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