Cjoerg
Cjoerg

Reputation: 1325

How to sort an array of mongoid documents (array contains different mongoid document types)?

I have two arrays of Mongoid documents, FirstType documents and SecondType documents. Both are embedded in User.

user.first_types  =  [#<FirstType _id: 51a10b4883c336ebef0002a8, created_at: 2013-05-25 19:04:40 UTC, updated_at: 2013-05-25 19:04:40 UTC, datetime: 2013-03-28 15:03:22 UTC, text: "Hello 1">]
user.second_types = [#<SecondType _id: 51a6058783c3368a62000003, created_at: 2013-05-29 13:41:27 UTC, updated_at: 2013-05-29 13:41:27 UTC, datetime: 2013-05-29 08:23:27 UTC, text: "Hello 2">]

Then I merge them with this line of code:

all_types = user.first_types+user.second_types

I now wish to sort the all_types array by the attribute datetime (newest datetime first, so the SecondType object should be the first one).

I have tried the conventional Mongoid and Ruby array methods, but they don't seem to work when I mix up Mongoid documents. Any ideas?

Upvotes: 0

Views: 874

Answers (1)

maerics
maerics

Reputation: 156434

Use Enumerable#sort_by and negate the numeric value of the "datetime" attribute for descending order:

all_types.sort_by { |x| -x.datetime.to_f }

Upvotes: 5

Related Questions