A Note on ActiveRecord Serialization and Objects

Let’s say you’re serializing a ruby object for later use in a field of another model.

class Foo < ActiveRecord::Base
  serialize :bar
end

In this instance, assume an object of type “Bar” is what’s being serialized. After save, the data appears fine, but when you retrieve the data, instead of your Object you end up with yaml that looks like this:

[#<YAML::Object:0x3fcade8 @ivars={"attributes_cache"=>{}, "attributes"=>{"updated_at"=>"2008-11-04 19:33:05", "id"=>"1", "message"=>"Hello World!", "created_at"=>"2008-11-04 19:33:05"}}, @class="Bar">

This most likely means that the model of the object being serialized is not loaded yet. This can be resolved by simply doing:

class Foo < ActiveRecord::Base
  Bar

  serialize :bar
end

This will load the model before serialization occurs and you’ll be all set.

One Response to “A Note on ActiveRecord Serialization and Objects”

  1. Kris says:

    Should you not include the class name eg.

    serialize :bar, Bar

    I think it defaults to Hash or maybe Object if not…

Leave a Reply