Serialized Attributes Rails 3 1

Posted by arunagw on August 27, 2011

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 
end
user = User.find 1
user.preferences = {:foo =>  'bar'}
user.save

So now we can pass a second parameter to serialize method to use that serialization method.

class User < ActiveRecord::Base
  serialize :preferences, SomeCoolEncoder.new
end

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
    value.unpack('m').last
  end

  def dump(text)
    [text].pack('m')
  end
end

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}
  end

end

# So you can use like 

post = Post.new
post.serializable_hash   # => {"title"=>nil}
post.name = "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

Trackbacks

Use this link to trackback from your own site.

  • Manojs Nitt

    @arun 

    An object has lots of references
    example, @user.friends,   @user.scraps
    for that user both friends & scraps has more that 100,

    My question is
    If we serialize  @user  object, will it serialize its associated objects also?

    Thanks,

    Jon


Follow

Get every new post delivered to your Inbox

Join other followers