Can I save as Model's property as a hash?
I want to do the following.
I want my model to have a column that s开发者_如何学运维tore'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?
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 }
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"
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)
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
精彩评论