Rails ActiveRecord Data Serialize

Recently I ran into a problem in my application where I had to store multiple Boolean values in the DB. There  are many ways to do this, but I wanted to implement it in the most efficient way. One of the method  is create that many number of specific columns in your table store the data, but for that we had to create ‘n’ of columns in the db which was not a promising solution.

On digging a little more deeper, I found out that hashes can be stored in a single column of a database, this is known as “Serialization” in rails. I had this implemented in my app which was simple and elegant to store my data as hash, and the retrieving of the data was also much more simpler. In my case I needed to have three Boolean fields stored in a hash under a single column in the DB. Let me walk you through the steps as in how I implemented it.

I Had model ‘user.rb‘ to which I needed to add a column ‘:boarding_skip_steps_status‘, for this I generated a migration file with a text field. This is how my migration file looks:

class AddOnBoardingStatusToUsers < ActiveRecord::Migration
 def change
  add_column :users, :boarding_skip_steps_status, :text, :default => {:facebook => false, :follow   => false, :travelogue => false}.to_yaml

  User.update_all(["boarding_skip_steps_status = ?", {:facebook => false, :follow => false,   :travelogue => false}.to_yaml])
 end
end

Let me explain what is being done here, I’m adding a column to the users table and setting it to default. You can notice the use of “to_yaml” method being used,  the reason is that when rails stores an hash value in the DB it converts the hash to YAML format. The line of code updates your existing users with the defaulted hash.

In your User model, add the line,

serialize :boarding_skip_steps_status
attr_accessible :boarding_skip_steps_status

and that’s it, now you can store and retrive the values just like your normal any other attributes in the object.

See the below O/P:

To Store Data:

=> u= User.find(22)
=> u.boarding_skip_steps_status = {:facebook=>true, :follow=>true, :travelogue=>false}
=> u.save

To retrieve the data:

=> U = User.find(22)
=> <#User id: 22, email: "abc@gmail.com",  created_at: "2014-09-25 06:41:46", updated_at: "2014-10-11 13:19:49", on_boarding_status: false, boarding_skip_steps_status: {:facebook=>true, :follow=>true, :travelogue=>false}>
=> U.boarding_skip_steps_status
=> {:facebook=>true, :follow=>true, :travelogue=>false}
=> U.boarding_skip_steps_status[:facebook]
=> true

To update data:

=> U.boarding_skip_steps_status[:facebook] = false
=> U.save

Thats all  an hash of data is stored in the DB, hope it helps you!

Thanks For Reading!

reference:apidock rails.