Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute was supposed to be a Array, but was a ActionController::Parameters

I am getting the following error:

ActiveRecord::SerializationTypeMismatch at /classifications
Attribute was supposed to be a Array, but was a ActionController::Parameters. -- {"1"=>"pumpkin text"} 

In my classification model, I have the following serialization which corresponds with a mysql column named default_fields of type text:

serialize :default_fields, Array

In my view the name attribute looks like so:

<input id="classification_default_fields_n" name="classification[default_fields][1]" type="checkbox" value="pumpkin text">

And I could have multiple fields like this:

<input id="classification_default_fields_n" name="classification[default_fields][2]" type="checkbox" value="cucumber text">
<input id="classification_default_fields_n" name="classification[default_fields][3]" type="checkbox" value="orange text">

As you can see, I am expecting an array of strings in the variable default_fields. However, it is not trying these fields as an array. It is treating them as a hash of key/value pairs.

How can I address this?

like image 344
Donato Avatar asked Dec 09 '25 05:12

Donato


1 Answers

Ok, I get it now. If you want to send an array, then the brackets must be empty like so:

classification[default_fields][]"

If you want to send a hash, then the square bracket must contain a value that represents the key and the value is represented by the input data:

classification[default_fields][1]

Now if you want to send a collection (hash) of hashes, then the value in the brackets indicates the key of one of the hash elements:

classification[default_fields[1][key1]]
classification[default_fields[2][key2]]

Also add the correct serialization for what you want:

  serialize :default_fields, Hash
  # or
  serialize :default_fields, Array
like image 126
Donato Avatar answered Dec 11 '25 20:12

Donato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!