serialize
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (1)
- 2.0.3 (17)
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (-2)
- 3.1.0 (1)
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
serialize(attr_name, class_name = Object)
public
If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically. The serialization is done through YAML. If class_name is specified, the serialized object must be of that class on retrieval or SerializationTypeMismatch will be raised.
Parameters
-
attr_name - The field name that should be serialized.
-
class_name - Optional, class name that the object type should be equal to.
Example
# Serialize a preferences attribute class User < ActiveRecord::Base serialize :preferences end
Another Example
Do not mistakenly pass class_name as a key/value pair (Hash form). You will get an error including the text ‘class or module needed’. It should look like this:
serialize :some_array, Array
Or, perhaps clearer would be:
serialize(:some_array, Array)
That may seem obvious, but it is common to be in the habit of passing things as a key/value pair.
Beware - May cause performance issues
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
bad
product = Product.first product.save
good
product = Product.first product.save if product.changed?
Do not mistakenly use serialize like other similar directives - attr_accessible, attr_accessor
serialize seems very similar to other directives that work on attributes such as attr_accessible. One may mistakenly assume that serialize can take a list of attributes. For eg:
class Tuk < ActiveRecord::Base attr_accessible :foo, :bar serialize :foo, :bar end
This may lead to a cryptic error. Eg.
puts !Tuk.first.foo.nil?
causes:
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.