Ruby on Rails: Submitting an array in a form

Ruby on-RailsArraysFormsHash

Ruby on-Rails Problem Overview


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"

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

= simple_form_for @article do |f|
  = f.input_field :name, multiple: true
  = f.input_field :name, multiple: true
  = f.submit

Solution 3 - Ruby on-Rails

TL;DR version of HTML [] convention:

Array:

<input type="textbox" name="course[track_codes][]", value="a">
<input type="textbox" name="course[track_codes][]", value="b">
<input type="textbox" name="course[track_codes][]", value="c">

Params received:

{ course: { track_codes: ['a', 'b', 'c'] } }

Hash

<input type="textbox" name="course[track_codes][x]", value="a">
<input type="textbox" name="course[track_codes][y]", value="b">
<input type="textbox" name="course[track_codes][z]", value="c">

Params received:

{ course: { track_codes: { x: 'a', y: 'b', z: 'c' } }

Solution 4 - Ruby on-Rails

I've also found out that if pass your input helper like this you will get an array of courses each one with its own attributes.

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

# will become the Array 
   params["course"]

# where you can get the values of all your attributes like this:
   params["course"].each do |course|
       course["track_codes"]
   end    

Solution 5 - Ruby on-Rails

I just set up a solution using jquery taginput:

http://xoxco.com/projects/code/tagsinput/

I wrote a custom simple_form extension

# for use with: http://xoxco.com/projects/code/tagsinput/

class TagInput < SimpleForm::Inputs::Base

  def input
    @builder.text_field(attribute_name, input_html_options.merge(value: object.value.join(',')))
  end

end

A coffeescrpt snippet:

$('input.tag').tagsInput()

And a tweak to my controller, which sadly has to be slightly specific:

@user = User.find(params[:id])
attrs = params[:user]

if @user.some_field.is_a? Array
  attrs[:some_field] = attrs[:some_field].split(',')
end

Solution 6 - Ruby on-Rails

I had a similar issue, but wanted to let the user input a series of comma separated elements as the value for the array. My migration uses rails new ability (or is it postrges' new ability?) to have an array as the column type

add_column :articles, :links, :string, array: true, default: []

the form can then take this input

<%= text_field_tag "article[links][]", @article.links %>

and it means the controller can operate pretty smoothly as follows

def create
  split_links
  Article.create(article_params)
end

private
def split_links
  params[:article][:links] = params[:article][:links].first.split(",").map(&:strip)
end


params.require(:article).permit(links: [])

Now the user can input as many links as they like, and the form behaves properly on both create and update. And I can still use the strong params.

Solution 7 - Ruby on-Rails

For those who use simple form, you may consider this solution. Basically need to set up your own input and use it as :array. Then you would need to handle input in your controller level.

#inside lib/utitilies
class ArrayInput < SimpleForm::Inputs::Base
  def input
    @builder.text_field(attribute_name, input_html_options.merge!({value: object.premium_keyword.join(',')}))
  end
end

#inside view/_form

...
= f.input :premium_keyword, as: :array, label: 'Premium Keyword (case insensitive, comma seperated)'

#inside controller
def update
  pkw = params[:restaurant][:premium_keyword]
  if pkw.present?
    pkw = pkw.split(", ")
    params[:restaurant][:premium_keyword] = pkw
  end

  if @restaurant.update_attributes(params[:restaurant])
    redirect_to admin_city_restaurants_path, flash: { success: "You have successfully edited a restaurant"}
  else
    render :edit
  end   
end

In your case just change :premium_keyword to the your array field

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliam JonesView Question on Stackoverflow
Solution 1 - Ruby on-RailsLarry KView Answer on Stackoverflow
Solution 2 - Ruby on-RailsstAndreiView Answer on Stackoverflow
Solution 3 - Ruby on-RailsecoologicView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAna FrancoView Answer on Stackoverflow
Solution 5 - Ruby on-RailsPeter EhrlichView Answer on Stackoverflow
Solution 6 - Ruby on-Railsian rootView Answer on Stackoverflow
Solution 7 - Ruby on-RailssovanlandyView Answer on Stackoverflow