Serialize not working as expected. Am I doing it wrong?

I reported the bug here:

But the replies are to the tone of "it's not a bug". Serialize isn't
working how I expect it to, but I was wondering if I'm just looking at
it all wrong.

The code I'm using is essentially what you see in the bug report.


The serialized Array is getting unserialized correctly.

However, I think YAML needs to know about the Peg class before you can
unserialize if you want the elements of the array to be Peg
instances. Like someone at the rails bug tracker, I think you need to
require and/or include peg.rb. One solution is to have the Peg class
defined in board.rb before the Board definition (or maybe after).
This worked for me:

class Peg
  def meth

class Board < ActiveRecord::Base
  serialize :pegs

Loading development environment (Rails 2.1.0)

b =

=> #<Board id: nil, pegs: nil, created_at: nil, updated_at: nil>


=> nil

b.pegs = []

=> []


=> [#<Peg:0xb7683adc>]

=> true

b = Board.find 1

=> #<Board id: 1, pegs: [#<Peg:0xb766ec90>], created_at: "2008-07-18
19:58:01", updated_at: "2008-07-18 19:58:01">


=> "foo"

I mentioned in my original post on the bug tracker that you either
need to include or require peg.rb (or write the class inside board.rb
like you did).

My point is that it doesn't seem like the expected behavior.

It seems like rails should automatically include/require the class for
you, just like it always would. I'm not sure if that responsibility
should be on YAML or on ActiveRecord, but it seems that it should be
done automagically by one of the classes involved.

I don't think it can be ActiveRecord: it doesn't understand yaml at
all, it just gets a blob of data which it hands off to yaml. Yaml
being a pure ruby thing doesn't do the magic autoloading stuff that
rails does and so you're stuck.


That's the thing, YAML *does* do all sorts of autoloading. All it has
it text, and it turns that into the proper classes.

I do think you have a point about the separation, Frederick.

I would make the assumption that YAML has a list of folders it looks
in when loading classes. If that were publicly accessible (IE - Rails
could access it), then all rails would have to do is add the app/
models/* folders and app/lib/* folders to that list of autoloading

But I'm probably making too many assumptions there.

I find it unexpected behavior that I read your ticket and didn't read
the solution you posted right before posting the exact same solution :-

Anyways, you might want to check this out if you haven't already: