Using serialize option in Ruby on Rails
In this post, I am going to show you how to make use of serialize
option in Ruby on Rails so that you can store information in your database more efficiently.
First of all, have you ever been in a situation which you want to store an array or a hash as a value in a table column? Imagine that you have an user model and each user would have many tags. I have seen someone (including me) doing something like this:
user.tags = "sports,science,engineer"
and when retrieving the values
tags = user.tags.split(",")
You can see that every time we need to get list of tags, we have to split
the string value to get an array. And it is not very comfortable to us, intelligent developers.
Things would be worse if you need to store a hash as a value in a column. You have to convert the hash into string and then parse the string to get the hash every time you work with that column. We need a better way, and we already have that. Rails offer serialize
option inside an ActiveRecord model which we can specify what kind of data are stored in a column and Rails would automatically take care of converting/parsing the actual values. Let's go back to previous User model
class User < ActiveRecord::Base
serialize :tags, Array
serialize :course, Hash
end
In this model, I have two columns: tags
and course
. I am going to store an array into tags
and a hash into courses
. For example:
user = User.new
user.tags = ["sports", "science", "engineer"]
user.tags # => ["sport", "science", "engineer"]
user.course = {id: 1, name: "History"}
user.course # => {id: 1, name: "History"}
Please be noted that you should specify the correct data type you want to store so that you would 100% sure to retrieve the value back in correct data type (Rails use YAML
by default to convert the data). In addition, you have to use text
data type when creating this column in migration because Rails will convert all those object into plain text when storing in database. You can check it in your DBMS Tool and you will see how Rails do that.
You can read more here: http://apidock.com/rails/ActiveRecord/Base/serialize/class
Note
If you have serialized column in your model then this column will always be updated when you update your model, even though you make no changes to the values in that selialized column. So don't try to use this extensively in your app as it could affect the overall performance.
Have a great day!