BinaryWebPark

How To Save Nested Attribute Checkboxes With Formtastic and Cocoon and Avoid the TypeError

September 14, 2014

Avoiding the TypeError: can’t cast Array to string

Recently, I was inserting nested attribute checkboxes using

Formtastic and Cocoon and was cruising along with all my other nested forms partials until I got a dreaded TypeError: can’t cast Array to string.

Below is the pertinent code pattern I used that worked for other parts of my nested form:

Code for the form view using Formtastic

= semantic_form_for @person, url: {action: "update_something_action" } do |f|
%h4 Papers
#papers
  = f.semantic_fields_for :papers do |paper|
    = render 'paper_fields', :f => paper
    .links
      = link_to_add_association 'Add paper', f, :papers

Code for the form partial \paperfields.html.haml using Formtastic and Cocoon

.nested-fields
  = f.inputs :name => "Paper" do
  = f.input :paper_title
  = f.input :paper_year
  = f.input :good_paper, as: :check_boxes, collection: ["Yes", "No"]
  = link_to_remove_association "Remove paper", f

The code for the form view and form partial above worked except for the check boxes which kept giving the TypeError: can’t cast Array to string.

Below is how I fixed this.

Step 1: Setup the parent model, Person, correctly

class Person < ActiveRecord::Base
  has_many :papers, dependent: :destroy
  accepts_nested_attributes_for :papers, allow_destroy: true
end

Step 2: Serialize goodpaper_ in Paper.rb

You serialize the attribute you want checkboxes for as follows:

class Paper < ActiveRecord::Base
  belongs_to :person

  serialize :citation_status, Array
end

Step 3: Setup FactoryGirl correctly

In spec/factories/paper.rb, we have:

FactoryGirl.define do
  factory :paper do
  paper_title "MyText"
  paper_year "MyString"
  citation_status ["",""]
  association :person
  end
end

And that’s it, your Rails 4 application nested attribute checkboxes should now be working correctly with Cocoon and Formtastic.