instance method to_form_params

Ruby on Rails 8.0.4

Since v5.2.8.1 Private

Available in: v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

to_form_params(attribute, namespace = nil)

Returns an array of hashes each containing :name and :value keys suitable for use as the names and values of form input fields:

to_form_params(name: 'David', nationality: 'Danish')
# => [{name: 'name', value: 'David'}, {name: 'nationality', value: 'Danish'}]

to_form_params(country: { name: 'Denmark' })
# => [{name: 'country[name]', value: 'Denmark'}]

to_form_params(countries: ['Denmark', 'Sweden']})
# => [{name: 'countries[]', value: 'Denmark'}, {name: 'countries[]', value: 'Sweden'}]

An optional namespace can be passed to enclose key names:

to_form_params({ name: 'Denmark' }, 'country')
# => [{name: 'country[name]', value: 'Denmark'}]

Parameters

attribute req
namespace opt = nil
Source
# File actionview/lib/action_view/helpers/url_helper.rb, line 780
        def to_form_params(attribute, namespace = nil)
          attribute = if attribute.respond_to?(:permitted?)
            attribute.to_h
          else
            attribute
          end

          params = []
          case attribute
          when Hash
            attribute.each do |key, value|
              prefix = namespace ? "#{namespace}[#{key}]" : key
              params.push(*to_form_params(value, prefix))
            end
          when Array
            array_prefix = "#{namespace}[]"
            attribute.each do |value|
              params.push(*to_form_params(value, array_prefix))
            end
          else
            params << { name: namespace.to_s, value: attribute.to_param }
          end

          params.sort_by { |pair| pair[:name] }
        end

Defined in actionview/lib/action_view/helpers/url_helper.rb line 780 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::UrlHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close