John
John

Reputation: 13735

Ordering an array of rails active record objects by an attribute of objects

I am querying my database to come up with a list of activities, and I would like them ordered in descending order by the updated_at attribute. I get this list of activities by going through two other models and doing maps, i.e.:

@listings = current_user.listings.includes(:deals)
map_of_listings = @listings.map { |listing| listing.deals }
@deals = map_of_listings.flatten

map_of_deals = @deals.map { |deal| deal.activities }
activities_array = map_of_deals.flatten

The problem for me now is that the activities in the array are grouped by deal, instead of being listing in descending order by when they were last updated. How can I order this array by the updated_at attribute of activity?

Upvotes: 2

Views: 721

Answers (1)

Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

If you're on Ruby 1.9, you could try

activities_array.sort_by(&:updated_at)

Upvotes: 2

Related Questions