Saving Arrays, Hashes, and Other Objects In Text Columns Using Active Record

Have you ever wanted to store an array, hash or object in a database column?  Using Active Record and YAML makes this completely painless.  To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.

Class_ ActiveRecord__Base

You can also specify a class option as the second parameter that‘ll raise an exception if a serialized object is retrieved as a descendant of a class not in the hierarchy.

Class: ActiveRecord::Base

Nothing new here, but something that can be pretty powerful.  Working with people not used to Ruby or ActiveRecord brings back some of the nice “magic” we take for granted on a regular basis. (Samples taken directly from Ruby on Rails API Documentation)

2 thoughts on “Saving Arrays, Hashes, and Other Objects In Text Columns Using Active Record

  1. Nice. For DataMapper, I’d do something like this:

    class Model
    include DataMapper::Resource
    property :id, Serial
    property :column, Text

    before :save do
    attribute_set(:column, column.to_yaml) unless column.is_a?(String)
    end

    def column
    @column ||= YAML.load(attribute_get(:column))
    end
    end

    It does make me wonder if there is something similar for DM, though. Also, I’ve not tested the code, it’s proof of concept only. 🙂

  2. The YAML serializer can be painfully slow… I typically use the same technique but use the JSON serializer since it’s faster (not pure). I usually just override the attribute acessors with my dump/load code (one of these days I will create my own plugin). The fastest technique is to use Marshal but it’s not guaranteed to be forwards compatible.

Step up to the mic.

Your email address will not be published.