← Back to Upcase

How to create an array of parameters with form helpers?

(Yevgeniy Viktorov) #1

Basically I want it to produce something like this:

<input name="addresses[][line1]" type="text"/>
<input name="addresses[][line2]" type="text"/>
<input name="addresses[][city]" type="text"/>

And then expect params[:addresses] to be an array.

I used fields_for with index, but that produces a hash upon submission, e.g.:

<%= f.fields_for :addresses, index: 1 do |builder| %>
  <%= render 'addresses', f: builder %>
<% end %>

# =>

<input name="addresses[1][line1]" type="text"/>
<input name="addresses[1][line2]" type="text"/>
<input name="addresses[1][city]" type="text"/>

I also tried few examples from http://guides.rubyonrails.org/form_helpers.html but it didn’t worked for some reason… Any idea how to omit the index value while keep the square brackets? (rails 4.0.2 here)

Thanks in advance.

(Luís Ferreira) #2

@wik You can use the name property.

<%= text_field :line1, name: "addresses[][line1]" %>

This will create an array of hashes:

"addresses"=>[{"line1"=>"example", "line2"=>"address", "city"=>"somewhere"}]

I believe rails will always create an hash, in order to associate the field name with its value. If this is not the format you want, you can format it when it gets to the controller.