Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

serialize'd array not unserializing properly

#647

I don't have time to make a patch for this, but I wanted to bring it to everyone's attention.

Take this code as an example

class Peg
  # does not inherit from ActiveRecord
  def some_method
     "foo"
  end
end

class Board < ActiveRecord::Base
  serialize :pegs
  def setup_pegs
    self.pegs = [Peg.new, Peg.new, Peg.new]
  end
end

class SomeController < ApplicationController
  def index
    b = find_or_create_board
    b.pegs[0].some_method  # IMPORTANT LINE!
  end
  
  def find_or_create_board
    b = Board.find(:first)
    if b.nil?
      b = Board.new
      b.setup_pegs
      b.save!
      b
    end
  end
end

This code will work fine the first time though because it creates new Peg objects. The second time through, when it has to load the pegs from the database, the "b.pegs[0].some_method" will result in a NoMethodError because the "pegs" array actually looks (something) like this:

"#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">",

"#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">",

"#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">"

It is an array of YAML objects instead of an array of Pegs, therefor, it doesn't have "some_method" like you would expect. I learned form this helpful blog that adding

require 'peg'

to the top of the Board class will solve this problem. The reason it is happening is because the YAML loading method can't find the Peg class and defaults to making it a YAML object.

Reported by auzigog · July 18th, 2008 @ 08:14 PM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. auzigog
    auzigog

    Sorry, those #'s in the middle were supposed to look like this:

    "#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">",

    "#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">",

    "#<YAML::Object:0x52cc220 @ivars={}, @class="Peg">"

    July 17th, 2008 @ 10:34 PM

  2. RSL
    RSL

    How is this not a has_many association?

    July 17th, 2008 @ 10:38 PM

  3. auzigog
    auzigog

    Because Peg is not a model? It doesn't deserve to be a model. There are hundreds of pegs per row and there is no point in wasting tons of database rows with simple objects that could easily be serialized instead.

    July 17th, 2008 @ 10:39 PM

  4. auzigog
  5. Phil Orwig
    Phil Orwig

    Shouldn't including peg.rb in lib/ do the trick for this?

    July 18th, 2008 @ 02:19 AM

  6. Pratik
    Pratik
    • State changed from new to invalid

    Use composed_of.

    July 18th, 2008 @ 05:30 PM

  7. auzigog
    auzigog

    Am I wrong in assuming that serialize isn't working as expected?

    Using composed_of doesn't resolve that unexpected behavior, it just fixed my problem.

    July 18th, 2008 @ 08:06 PM