Request param type of array

Hello.

I have tested such form:

================
After submitting my form:

<% raise params.inspect %>

{“myfield”=>“value1”, “action”=>“index”, “_submit”=>“OK”,
“controller”=>“params”}

<% raise request.cgi.params.inspect %>

{“myfield”=>[“value1”, “value2”], “_submit”=>[“OK”]}

================

In Rails source code I have found such code:
—> actionpack-1.13.5/lib/action_controller/cgi_ext/cgi_methods.rb
(line 23):

def parse_request_parameters(params)
  parser = FormEncodedPairParser.new

  params = params.dup
  until params.empty?
    for key, value in params
      if key.blank?
        params.delete key
      elsif !key.include?('[')
        # much faster to test for the most common case first (GET)
        # and avoid the call to build_deep_hash
        parser.result[key] = get_typed_value(value[0])
        params.delete key
      elsif value.is_a?(Array)
        parser.parse(key, get_typed_value(value.shift))
        params.delete key if value.empty?
      else
        raise TypeError, "Expected array, found #{value.inspect}"
      end
    end
  end

  parser.result
end

=============

Why from cgi-param type of array (for array with length 2 and more)
rails gets only first value?

Hi,

try to use the name ‘myfield[]’. That way you are telling rails that you
are expecting an array and that you want to access that param as such.
After that it should be working as you’d expect.

Guess the rationale after that is that since there is no clear way to
tell in plain html that you are going to use a multivalued field, you
should be checking always at the backend if you have a single or
multivalued param. Also you could get wrong results when having a
duplicated name in a view (as is the case sometimes).

By forcing a special syntax, you can be sure you are getting what you
are asking for. Even if you are finally passing a single value you can
safely access it as an array.

regards,

javier ramírez

I have found variant to send array of values and get them from params
variable:

Thanks :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs