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 hashes?)
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: