How to use serialized object in Active Record using Rails?

Serializing Object Will help us to store multiple column values in single Database column and even making processing using that column simple. It helps to extended the table without adding new column in table. Because we can store multiple column values in single column as Hash value.

So, It reduce the difficulty of retriving and storing datas into the database. Here I have given some guidelines to implement serializing data’s using our rails application

— In Sql Query creating new table called users
CREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `user_name` varchar(255), `group_id` int(11), `is_active` tinyint(1), `preferences` text, `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB

# in model, setting preference column as serializable object
class Utility < ActiveRecord::Base
serialize :preferences

# Storing values in serializable object
user =
user.preferences = {:account_locked => true, :password_failed_attempt => 2, :time_zone => "IST",…}

# Retriving value from the serializable object
user = User.find(1)
user.preferences # => {:account_locked => true, :password_failed_attempt => 2, :time_zone => "IST",…}
user.preferences[:account_locked] # => true
user.preferences[:password_failed_attempt] # => 2
user.preferences[:time_zone] # => "IST"

Permanent link to this article:

Leave a Reply

Your email address will not be published.