Ruby on Rails:将表单输入解释为整数
我有一个允许用户组合哈希值的表单。
散列所需的最终格式将是这样的:
{1 =>; “一”,2 => “x”,3 => 我可以
通过在名称中包含大量输入来构建类似的东西:
<%= hidden_field_tag "article[1]", :value => a %>
但是,最终结果是构建一个散列,其中所有键都是字符串而不是整数:
{“1”=>; “一”,“2”=> “x”,“3”=> 。
我目前正在通过循环输入哈希在控制器中生成新哈希来修复此问题,然后将其分配给参数 有没有更干净、更干燥的方法来做到这一点?
I've got a form that allows the user to put together a hash.
The hashes desired end format would be something like this:
{1 => "a", 2 => "x", 3 => "m"}
I can build up something similar by having lots of inputs that have internal brackets in their names:
<%= hidden_field_tag "article[1]", :value => a %>
However, the end result is that builds a hash where all the keys are strings and not integers:
{"1" => "a", "2" => "x", "3" => "m"}
I'm currently fixing this by generating a new hash in the controller by looping over the input hash, and then assigning that to params. Is there a cleaner, DRYer way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的参数将始终带有字符串键和值。解决此问题的最简单方法是编写自己的哈希扩展,或者只是根据需要注入:
然后您将拥有一个哈希,其中的键根据需要转换为整数值。
一个简单的扩展可能是:
这更加通用,可以按照以下方式使用:
Your params will always come in with string keys and values. The easiest way to fix this is to either write your own extension to Hash or simply inject as required:
Then you have a hash with the keys converted to integer values, as you like.
A simple extension might be:
This is much more generic and can be used along the lines of:
这有点取决于你想用它做什么。也许只使用字符串作为键,并在访问数组时进行“转换”(或根本不进行)会更容易?
也可以使用类似的方法构建一个数组,
将返回“article”作为数组,并且您可以通过索引直接访问它。但是,无法影响位置 - 数组将按出现顺序包含所有值。
最后,您可以制作自己的哈希版本或仅修改密钥,如前所述。
That depends a bit what you want to use it for. Maybe it is easier to just use strings as keys, and do the "conversion" when accessing the array (or not at all)?
It is also possible to build an array using something like
this will return "article" as an array, and you can access it directly by index. However, there is no way to influence the position - the array will contain all values in order of appearance.
Lastly, you can make your own version of Hash or just modify the keys, as has been explained.