serialize(attr_name, class_name = Object)public
Specifies that the attribute by the name of attr_name should be serialized before saving to the database and unserialized after loading from the database. The serialization is done through YAML. If class_name is specified, the serialized object must be of that class on retrieval, or nil. Otherwise, SerializationTypeMismatch will be raised.
# File activerecord/lib/active_record/base.rb, line 579 def serialize(attr_name, class_name = Object) serialized_attributes[attr_name.to_s] = class_name end
Or, perhaps clearer would be:
That may seem obvious, but it is common to be in the habit of passing things as a key/value pair.
A serialized attribute will always be updated during save, even if it was not changed. (A rails 3 commit explains why: http://github.com/rails/rails/issues/8328#issuecomment-10756812)
Guard save calls with a changed? check to prevent issues.
class Product < ActiveRecord::Base serialize :product_data end
class Tuk < ActiveRecord::Base attr_accessible :foo, :bar serialize :foo, :bar end
This may lead to a cryptic error. Eg.
NoMethodError at /file:location undefined method `new' for :bar:Symbol
This is because it tries to parse the YAML string stored in foo as an instance of :bar.