48

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 ?

5
  • 4
    If you're on postgres, it has array column type. Commented Jan 23, 2014 at 15:21
  • I'm using postgres : you recommend using their array column type ? Commented Jan 23, 2014 at 15:22
  • 3
    Obviously. Why would you want to mess with JSON, if you have arrays. Commented Jan 23, 2014 at 15:23
  • I'm using Rails 3.2 and it doesn't seem to support that function of PG Commented Jan 23, 2014 at 15:27
  • 1
    @titibouboul It is a good practice to add your stack details especially rails and ruby version in question by default. It saves a lot of your time and experienced people can answer better and faster (: Commented Dec 3, 2019 at 13:22

1 Answer 1

96

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm guessing the stuff field would be of type string when stubbing out the model?
To answer my own question, a type of string or text would work for this example, though text should be preferred since you don't want to accidentally run into the max length limit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.