0

i have the following form

 <%= simple_form_for(@software)  do |f| %>
 <%= f.input :softwarename, :collection => software_options, as: :check_boxes %>

And this helper.

module SoftwareHelper

def software_options
    ['7zip','SysInternals','Office','PDF-Creator']
end
end

My application controller looks like this

def software_params
    params.require(:software).permit(:softwarename => [])
end

And here is my software controller:

def new
    @software = Software.new
end

def create
    @software = Software.new(software_params)

    @software.save
    redirect_to @software
end

When I try to save the form input to my database (sqllite) i get the following error:

TypeError: can't cast Array to string

Do i have to convert the array to a string?

1
  • The collection option will make the data come through as an array. So you will need to convert this array to whatever form you store the data in the database, which you don't specify. How are you actually storing it? Commented May 19, 2014 at 14:16

1 Answer 1

2

You are receiving error as

TypeError: can't cast Array to string

because the attribute that you are trying to save i.e., softwarename is of type String in database and you are passing its value as an Array from the form (with checkboxes).

What you can do is mark softwarename attribute for serialization using serialize method, so that the Array passed as value of softwarename is converted to a String before saving it in database. This would also take care of deserialization from String to Array in case you are retrieving the attribute from database.

class Software < ActiveRecord::Base
  serialize :softwarename, Array  ## Add this line
  ## ...
end

Refer to serialize method documentation for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.