How ever in practice we have to store an object like Hash or Array into the database, like you want a hash to be store in the database and keys of the that hash used as like an attribute, For this kind of starage in the databse you can use ActiveRecord::Store
. Here is the sample implementation of this:
Introduction:
Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It’s like a simple key/value store baked into your record when you don’t care about being able to query that store outside the context of a single record.
You can then declare accessors to this store that are then accessible just like any other attribute of the model. This is very helpful for easily exposing store keys to a form or elsewhere that’s already built around just accessing attributes on the model.
Add serialized_options attributes:
- Add an attribute in the migration that will be a
text
type attribute.
- Run
rake db:migrate
.
Add store accessors in model:
- You have define store atribute in model and store accessors to access them like an attribute.
Accessing stored attributes:
- If store accessors define then simply you can access like an ordinary attribute. like:
- You can retrive data like:
- If store accessors not define then :
- The stored attribute names can be retrieved using .stored_attributes.
This is a sample implementation of store attributes in rails active record. Click here for more details about ActiveRecord::Store
.