0

I have a Comment model with a serialized attribute:

  serialize :edit, Hash

Each edit for the comment is timestamped by inserting a key/value pair:

self.edit[DateTime.current] = edit_content

How would I order a collection of comments, all sorted by the first submitted timestamp for each comment?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

1 Answers1

1

You can't. Your edit column stores the data as a serialized string, so basically its contents look like this:

[3] pry(main)> a = {}
=> {}
[4] pry(main)> a[DateTime.current] = 'bla'
=> "bla"
[5] pry(main)> a[DateTime.current] = 'bla bla'
=> "bla bla"
[9] pry(main)> a.to_yaml
=> "---\n!ruby/object:DateTime 2015-10-04 21:38:02.611020000 Z: bla\n!ruby/object:DateTime 2015-10-04 21:38:06.594140000 Z: bla bla\n"
[10] pry(main)> puts a.to_yaml
---
!ruby/object:DateTime 2015-10-04 21:38:02.611020000 Z: bla
!ruby/object:DateTime 2015-10-04 21:38:06.594140000 Z: bla bla
=> nil

In order to make it sortable by database, you need either extract your edits to another entity (such as Revision and create revisions table), or, for example, make a comments.first_edit_date column and sort by it as you usually do.

P.S. You can, of course, load all your comments table to memory and then order it there, but it will have huge performance implications:

# DON'T DO THIS IN PRODUCTION
Comment.all.sort_by { |comment| comment.edit.keys.first } 
Alexey Shein
  • 7,342
  • 1
  • 25
  • 38