Ruby on Rails: Submitting an array in a form

William Jones picture William Jones · Jun 22, 2010 · Viewed 85.1k times · Source

I have a model that has an attribute that is an Array. What's the proper way for me to populate that attribute from a form submission?

I know having a form input with a field whose name includes brackets creates a hash from the input. Should I just be taking that and stepping through it in the controller to massage it into an array?

Example to make it less abstract:

class Article
  serialize :links, Array
end

The links variable takes the form of a an array of URLs, i.e. [["http://www.google.com"], ["http://stackoverflow.com"]]

When I use something like the following in my form, it creates a hash:

<%= hidden_field_tag "article[links][#{url}]", :track, :value => nil %>

The resultant hash looks like this:

"links" => {"http://www.google.com" => "", "http://stackoverflow.com" => ""}

If I don't include the url in the name of the link, additional values clobber each other:

<%= hidden_field_tag "article[links]", :track, :value => url %>

The result looks like this: "links" => "http://stackoverflow.com"

Answer

Larry K picture Larry K · Jun 22, 2010

If your html form has input fields with empty square brackets, then they will be turned into an array inside params in the controller.

# Eg multiple input fields all with the same name:
<input type="textbox" name="course[track_codes][]" ...>

# will become the Array 
   params["course"]["track_codes"]
# with an element for each of the input fields with the same name

Added:

Note that the rails helpers are not setup to do the array trick auto-magically. So you may have to create the name attributes manually. Also, checkboxes have their own issues if using the rails helpers since the checkbox helpers create additional hidden fields to handle the unchecked case.