17

Looking for a simple method utilizing active record to grab data from two models, combine the data, and then sort the combined output by created_at.

For example:

assume two models, Comment & Like both belongs_to User

return a combined list of @user's comments and likes sorted by date

I know I can do this in SQL but I'd really like an active record solution.

Thanks!

istan
  • 1,349
  • 3
  • 21
  • 36

2 Answers2

25

I believe it should be as simple as:

combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }
Chris Barretto
  • 9,379
  • 3
  • 42
  • 45
  • this gets me closer, returning both query results in a single array but it does not mix them based upon created_at. It returns comments ordered by created_at followed by likes ordered by created_at. I need all the records mixed together so I get a chronological stream of commenting/liking activity – istan Jul 09 '11 at 07:47
  • 8
    This solution works, but has serious performance (memory) issues, since you are loading all records into memory and asking Ruby to do the sorting. I'd love an answer that used the database for the sorting. – sandre89 Oct 31 '16 at 19:24
0

How about something like (untested):

class User < ActiveRecord::Base
  scope :activities_by_date, :joins(:comments).joins(:likes).order("created_at desc")
end

Then you can do @user.activities_by_date and let the db do all the work

Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40