Serialization of ActiveRecord model fields – let AR do it and avoid much pain – Ruby on Rails 3.0.9, Ruby 1.9.2

Created an ActiveRecord model that had a single field that would hold a data structure that included a non-AR object as a part of a Hash that I wanted serialized to the database and de-serialized on retrieval.

Remembering my java days, I wrote a getter and setter to override ActiveRecord’s default getter and setter to do the serialization / de-serialization:

def myfield=( data )
  write_attribute( :myfield, YAML::dump( data ) )
end

def myfield
  YAML::load read_attribute( :myfield )
end

Easy enough and worked fine on my OSX and our Linux-based pair programming environments.  Check into trunk, let Jenkins build it and deploy to our Linux-based CI environment and BOOM!  Serialization failures all over the place.

Went down a long road of switching between ‘syck’ and ‘psych’ for YAML and Marshal (which requires ASCII-8BIT encoding and causes all sorts of encoding pain) … nothing worked.

Finally, I came across the serialize macro for ActiveRecord (that is what I get for not reading the docs *first*), which marks a field for serialization.

class MyClass < ActiveRecord::Base
  serialize :myfield
end

Voila! Code works everywhere – good ActiveRecord magic.

Hope this experience helps others having issues with serialization and ActiveRecord.

This entry was posted in Ruby on Rails. Bookmark the permalink.

Leave a comment