Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty array as default for active_record serialized attribute

I have an active record model:

class Person < ActiveRecord::Base
  serialize :tags, Array
end

and in the migration the tags column is declared as

t.text :tags, :default => []

but when I try to create a person

Person.new

I get the error

ActiveRecord::SerializationTypeMismatch: added was supposed to be a Array, but was a String

How do I set the default to be an empty array in the migration?

NB: I know I could do this using after_initialize but I prefer to set defaults in migrations

like image 913
opsb Avatar asked Feb 27 '11 15:02

opsb


3 Answers

There is an option to specify the class you want to store objects as. Try this:

class Person < ActiveRecord::Base
  serialize :tags, Array
end
like image 132
Peter Brown Avatar answered Nov 19 '22 10:11

Peter Brown


It sounds rather like you've hit a framework bug or something else is interfering with your migration; I just tried building the above with Rails 2.3.10 and can instantiate objects without problems. However, I note that YAML is used for serialisation, so:

t.text :tags, :default => [].to_yaml

...might do the trick. Both migrations seemed to behave equally in my test application.

like image 45
Andrew Hodgkinson Avatar answered Nov 19 '22 08:11

Andrew Hodgkinson


I had a similar issue and solved it by removing the default value. ActiveRecord will treat nil as [] when you begin to add values to the array.

Migration:
t.text :tags

Model:
class Person < ActiveRecord::Base
  serialize :tags, Array
end

Usage:
p = Person.new
p.tags << "test" 

This works because Rails will treat nil as [] for the array.

like image 2
vanboom Avatar answered Nov 19 '22 10:11

vanboom