This project is archived and is in readonly mode.
serialize'd array not unserializing properly
Reported by auzigog | July 18th, 2008 @ 08:14 PM | in 2.x
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.
Comments and changes to this ticket
-
auzigog July 17th, 2008 @ 10:34 PM
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">"
-
auzigog July 17th, 2008 @ 10:39 PM
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.
-
auzigog July 18th, 2008 @ 08:06 PM
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.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>