Rails: Serializing objects in a database?
I'm looking for some general guidance on serializing objects in a database.
- What are serialized objects?
- What are some best-practice scenarios for serializing objects in a DB?
- What attributes do you use when creating the column in the DB so you can use a serialized object?
- How to save a serialized object?
- And how to access the serialized object and its attributes? (Using h开发者_运维技巧ashes?)
In computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection link to be "resurrected" later in the same or another computer environment. (see http://en.wikipedia.org/wiki/Serialization)
So serialized objects (in the context of ActiveRecord) are text/string representations of objects (encoded using YAML). When serialized, you can save (almost) any Ruby object in a single database field.
You can use serialization if you have somewhat complex objects that you need to save in a database and you don't need to retrieve records based on the contents of a serialized attribute. I used them for example for storing preferences for users of a webapp: the preferences were basically hashes that I wanted to save in a single db field.
3./4./5. Use ActiveRecord::Base.serialize as Marc-André Lafortune suggested:
class User < ActiveRecord::Base
serialize :preferences
end
u = User.new
u.preferences = {:show_tooltips => true, :use_extended_menu => false, ...}
u.save
# ...
u = User.find(23)
u.preferences # => {:show_tooltips => true, :use_extended_menu => false, ...}
Really easy. Check the doc for ActiveRecord::Base.serialize
.
Have a look at MessagePack
If you are using Rails 4 with Postgresql, Rails 4 supports hstore field which can store hashes and allows queries too. http://blog.remarkablelabs.com/2012/12/a-love-affair-with-postgresql-rails-4-countdown-to-2013
精彩评论