Storing arrays in database : JSON vs. serialized array Storing arrays in database : JSON vs. serialized array arrays arrays

Storing arrays in database : JSON vs. serialized array


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

class Comment < ActiveRecord::Base  serialize :stuffendcomment = Comment.new  # stuff: nilcomment.stuff = ['some', 'stuff', 'as array']comment.savecomment.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, Arrayendcomment = 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.