开发者

Empty array as default for active_record serialized attribute

I have an active record model:

class Person < ActiveRecord::Base
  serialize :tags, Array
e开发者_如何转开发nd

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜