dc10
dc10

Reputation: 2208

How can I serialize - deserialize a hash in order to save it in the database?

I have a hash:

h = {
    "revision"=>7,         
    "rev"=>"708a4bd5b", 
    "thumb_exists"=>false, 
    "bytes"=>246000,     
    "modified"=>"Sun, 01 Jul 2012 17:09:15 +0000", 
    "client_mtime"=>"Sun, 01 Jul 2012 17:09:15     +0000", 
    "path"=>"/Getting Started.pdf", 
    "is_dir"=>false,       
    "icon"=>"page_white_acrobat", 
    "root"=>"dropbox",     
    "mime_type"=>"application/pdf", 
    "size"=>"240.2 KB"
}

I would like to save it in a database with the following command: h.to_s Then I would like to get the content from the database and to work with it as hash.

s = MyModel[:field_which_contains_hash_string]

I tried to load the content with YAML::load s but I get an error:

Psych::SyntaxError: (<unknown>): found unexpected ':' while scanning a plain scalar at line 1 column 96

I guess that's due to the colon in the time string. So what's the best way to persist the hash and retrieve it again?

Help is appreciated. Best, Philip

Upvotes: 9

Views: 12035

Answers (1)

aromero
aromero

Reputation: 25761

Create a column of type text in your model. Then in your model file do

class MyModel < ActiveRecord::Base
    serialize :column_name, Hash
end

Then access it using:

my_model = MyModel.new
my_model.column_name[:key] = value
my_model.column_name[:key]

The hash will be serialized into the column using YAML

http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize

Upvotes: 13

Related Questions