2

I want to do the following.

I want my model to have a column that store's a hash i.e. name/value pairs. When I load a record in my model, I don't want it to parse to de-seralize the value from the database UNLESS I access it i.e. lazy initialization.

This is b/c only a few percentage of my rows in the db will have values for the hash, and they will rarely be accessed.

Is this possible?

example usage:

user.properties["age"] = 12

user.properties["height"] = xxx

user.save

I'm not sure how it would be saved into the db, maybe in json format?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

5

Yes, you can serialize the data.

An excerpt from http://api.rubyonrails.org/classes/ActiveRecord/Base.html:

class User < ActiveRecord::Base
  serialize :preferences
end

user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }
vise
  • 12,713
  • 11
  • 52
  • 64
  • but this property will be de-serialized each time I load the object right? I want it lazy-de-serialized i.e. only if accessed – Blankman Mar 07 '11 at 16:30
1

ActiveRecord::Base#serialize Does just this.

class User < ActiveRecord::Base
  serialize :preferences, Hash
end

user = User.create(:preferences => { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }
User.find(user.id).preferences[:background] # => "black"
Unixmonkey
  • 18,485
  • 7
  • 55
  • 78
  • 1
    I stand corrected as I pasted the wrong excerpt, but you should have mentioned that in a comment. After posting just a link, then editing your post with the good excerpt and emphasising my mistake in your answer I can't help of finding the new recent edits that don't get saved process unfair. – vise Mar 06 '11 at 20:40
  • Good point. It would have been more tactful to comment on your almost correct answer. Sorry, It's no excuse, but I'm still new to StackOverflow and learning the ropes. I just want to help out fellow Rubyists. – Unixmonkey Mar 06 '11 at 21:31
0

it is worthy to add that for proper serialization the preferences column should have type of Text, see Using Rails serialize to save hash to database

Community
  • 1
  • 1
zeliboba7
  • 335
  • 1
  • 10
0

You can use a string as a data type, and save it the hash in yaml format. You need to load this yaml string, but IMHO gives you more portability.

hash = {a => b, c=>d}
object.properties = hash.to_yaml
.
.
.
hash = Yaml::load(object.properties)
Gareve
  • 3,372
  • 2
  • 21
  • 23