How to store an object in active record rails

Posted by : on

Category : Rails

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.
       
   def change
       add_column :table_name, :serialized_attr_name, :text
   end
  • 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.
class User < ApplicationRecord
  store :serialized_options, accessors: [:password_reset_token, :password_reset_sent_at], coder: Hash
  # here serialized_options is an attribute that will store a Hash. You have to define the ```coder: Hash/JSON```. If you
 don't define coder, by default it will be HASH. 

Accessing stored attributes:

  • If store accessors define then simply you can access like an ordinary attribute. like:
u = User.new(email: 'xyz@domain.com',password_reset_token: SecureRandom.uuid, password_reset_sent_at: Time.now)
  • You can retrive data like:
password_reset_token = User.password_reset_token
  • If store accessors not define then :
u = User.new(email: 'xyz@domain.com',password_reset_token: SecureRandom.uuid, password_reset_sent_at: Time.now)
    u.serialized_options[:temp_password] = SecureRandom.uuid
    # retrive like u.serialized_options[:temp_password]
  • The stored attribute names can be retrieved using .stored_attributes.
User.stored_attributes[:serialized_options] # will return [:password_reset_token, :password_reset_sent_at]

This is a sample implementation of store attributes in rails active record. Click here for more details about ActiveRecord::Store.



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in