titibouboul
titibouboul

Reputation: 1358

Storing arrays in database : JSON vs. serialized array

With ruby-on-rails, I want to store an array of 3 elements: the last 3 comments of a post. I know I could join the Comment table to the Post one, but I would avoid to do this heavy request for scaling purposes.

So I was wondering what was the best way to store those 3 elements, as I would like to update them easily every time a new comment is made: remove the last comment and add the new one.

What is the correct way to do this ? Store it in a serialized array or in a JSON object ?

Upvotes: 49

Views: 52119

Answers (1)

DiegoSalazar
DiegoSalazar

Reputation: 13531

You can store Arrays and Hashes using ActiveRecord's serialize declaration:

class Comment < ActiveRecord::Base
  serialize :stuff
end

comment = Comment.new  # stuff: nil
comment.stuff = ['some', 'stuff', 'as array']
comment.save
comment.stuff # => ['some', 'stuff', 'as array']

You can specify the class name that the object type should equal to (in this case Array). This is more explicit and a bit safer. You also won't have to create the array when you assign the first value, since you'll be able to append to the existing (empty) array.

class Comment < ActiveRecord::Base
  serialize :stuff, Array
end

comment = Comment.new  # stuff: []
comment.stuff << 'some' << 'stuff' << 'as array'

You can even use a neater version called store: http://api.rubyonrails.org/classes/ActiveRecord/Store.html

This should handle your use case using a built in method.

Upvotes: 96

Related Questions