Arun Agrawal’s Blog

Ruby on Rails Developer

Serialized Attributes Rails 3

This post will guide you how to do Serialization for your attributes in Rails. Serialize means you want to save arbitrary Ruby data structure into the database. Let consider we have a User model in which we want to store preferences for user in a Ruby data structure format. Previously it was only YAML.
class User < ActiveRecord::Base
  serialize :preferences 
user = User.find 1
user.preferences = {:foo =>  'bar'}
So now we can pass a second parameter to serialize method to use that serialization method.
class User < ActiveRecord::Base
  serialize :preferences,
You need to implement this encoder! It can be a JSON, XML, Base64. Or what every encoding technique you like to use. A sample encoder look like this.
class Base64Encoder
  def load(value)
    return unless value

  def dump(text)
This new encoder must have these methods in it! So now you attribute is serialized and you can store data in it in your given format. Ok so now we talk about ActiveModel::Serialization ActiveModel::Serialization will give you serialized attribute for your classes. A very simple example to use ActiveModel::Serialization
class Post

  include ActiveModel::Serialization

  attr_accessor :title

  def attributes
    {'title' => title}


# So you can use like 

post =
post.serializable_hash   # => {"title"=>nil} = "Rails is Cool!!"
post.serializable_hash   # => {"name"=>"Rails is Cool!!"}

Can use two inbuilt Serialization techniques
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
This is a very short intro for Serialization. Hope i will write more in detail soon!! I got this from @tenderlove talk in RailsConf2011