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

[sql]
— 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
[/sql]

[ruby]
# in model, setting preference column as serializable object
class Utility < ActiveRecord::Base
serialize :preferences
end
[/ruby]

[ruby]
# Storing values in serializable object
user = User.new
user.preferences = {:account_locked => true, :password_failed_attempt => 2, :time_zone => "IST",…}
user.save
[/ruby]

[ruby]
# 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"
[/ruby]

Permanent link to this article: https://blog.openshell.in/2013/11/how-to-use-serialized-object-in-active-record-using-rails/

Leave a Reply

Your email address will not be published.