Ruby on Rails: Interpreting Form Input as a Whole

I have a form that allows the user to compose a hash.

The hash of the desired end will be something like this: {1 => "a", 2 => "x", 3 => "m"}

I can create something like this, with many inputs that have internal brackets in their names:

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

However, the end result is that it builds a hash where all the keys are strings, not integers:
{"1" => "a", "2" => "x", "3" => "m"}

I am currently fixing this by creating a new hash in the controller, sorting through the input hash, and then assigning it to the parameters. Is there a cleaner, DRYer way to do this?

+3
source share
2 answers

Your parameters will always have string keys and values. The easiest way to fix this is to either write your own extension for Hash, or simply paste as needed:

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

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

A simple extension could be:

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

This is much more general and can be used line by line:

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

It depends a little on what you want to use it for. Maybe it's easier to just use strings as keys and perform a “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" %>

"" , . , - .

, Hash , .

+1

Source: https://habr.com/ru/post/1751796/


All Articles