Serialize ... what am I doing wrong?


#1

Hi.
I want to serialize out an object to the database. But I am getting an
integer value in the column when I expect to see some yaml!

migration:
class CreateSummaries < ActiveRecord::Migration
def self.up
create_table :summaries do |t|
t.text :summary_data
t.timestamps
end
end
end

class:
class Summary < ActiveRecord::Base
serialize :summary_data
end

example:
summary = Summary.new(:summary_data => User.first)
=> #<Summary id: nil, fss_player_id: nil, stats_type: nil, scope: nil,
summary_data: #<User id: 4, login: “LoginName”, email: “removed_email_address@domain.invalid”,
crypted_password: “cbc8411974ad085f608b6e0a05dd608e7577de19”, salt:
“ddc4528beea65095b7f5619912a6ca0681d0c10e”, created_at: “2008-09-12
18:43:19”, updated_at: “2009-02-05 04:20:58”, remember_token: nil,
remember_token_expires_at: nil, pw_reset_code: nil, role:
“commissioner”, sign_up_code:
“44e11a23be5b7833bf73d479a05166c0e0377c56”, reset_password_code_until:
nil, permalink: “fname”, name: “FName”, street: nil, city: nil,
province: nil, postcode: nil, country: nil, home_phone: nil,
mobile_phone: nil, display_name: “FName”, display_teams: true,
website: nil, occupation: nil, interests: nil, favourite_teams: nil,
anonymous_contact: false>, created_at: nil, updated_at: nil>

summary.save!
=> true

Summary.first.summary_data
=> 4

What am I doing wrong?


#2

Summary.new is expecting to receive a hash, which isn’t what you’re
giving it.

i.e.:
summary = Summary.new( :summary_data => { “name”=>“Administator”,
“login”=>“admin” } )

summary.save!

Summary.last.summary_data
=> {“name”=>“Administrator”, “login”=>“admin”}


#3

Oh! I thought the point was that I could save any object… are you
saying I can only save hash’s?


#4

Try this out (assuming you’ve got a User with id == 1):

summary = Summary.new(:summary_data => User.find(1).attributes).save!

Go here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html and
search for serialize


#5

I picked on the hash since that was your example - what appeared to be
a User record. Yes, you can save anything you want, it’s only yaml
after all…

So the :summary_data from your example maps on to a series of
name<>value tuples. Other languages refer to this as marshalling, I
seem to recall that Ruby has some functions with marshall in their
name.

Rails likes to talk about serializing and attribute lists,
ActiveRecord provides the attributes method as an easy way to
serialize the record’s fields.