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
There is an option to specify the class you want to store objects as. Try this:
class Person < ActiveRecord::Base
serialize :tags, Array
end
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With