Ruby on Rails:将表单输入解释为整数

发布于 2024-09-07 05:35:53 字数 357 浏览 5 评论 0原文

我有一个允许用户组合哈希值的表单。

散列所需的最终格式将是这样的:
{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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹿! 2024-09-14 05:35:53

您的参数将始终带有字符串键和值。解决此问题的最简单方法是编写自己的哈希扩展,或者只是根据需要注入:

numeric_keys = params['article'].inject({ }) do |h, (k, v)|
  h[k.to_i] = v
  h
end

然后您将拥有一个哈希,其中的键根据需要转换为整数值。

一个简单的扩展可能是:

class Hash
  def remap_keys
    inject({ }) do |h, (k, v)|
      h[yield(k)] = v
      h
    end
  end
end

这更加通用,可以按照以下方式使用:

params['article'].remap_keys(&:to_i)

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:

numeric_keys = params['article'].inject({ }) do |h, (k, v)|
  h[k.to_i] = v
  h
end

Then you have a hash with the keys converted to integer values, as you like.

A simple extension might be:

class Hash
  def remap_keys
    inject({ }) do |h, (k, v)|
      h[yield(k)] = v
      h
    end
  end
end

This is much more generic and can be used along the lines of:

params['article'].remap_keys(&:to_i)
抱着落日 2024-09-14 05:35:53

这有点取决于你想用它做什么。也许只使用字符串作为键,并在访问数组时进行“转换”(或根本不进行)会更容易?

也可以使用类似的方法构建一个数组,

<%= hidden_field_tag "article[]", :value => "x" %>

将返回“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

<%= hidden_field_tag "article[]", :value => "x" %>

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文