My setup: Rails 3.0.9, Ruby 1.9.2
Here are my models
class Project
has_many :tasks
has_many :photos
class Task
belongs_to :project
class Photos
belongs_to :project
What I need is to be able to return a result set sorted first by project name (ASC) and then interleave tasks and photos sorted by date (DESC). Here’s a sample output of the order I need
project: install new roof
photo: ...(added on 7/15/11)
task: ...(added on 7/10/11)
task: ...(added on 7/1/11)
project: repair bathtub
task: ... (added on 8/21/11)
photo: ... (added on 8/20/11)
photo: ...(added on 8/17/11)
task: ... (added on 8/15/11)
I prefer to get the entire result set from ActiveRecord and then sort it in Ruby but unsure how to go about it, any insights will be much appreciated. Thanks.
How about something like this? Grab all the objects, eagerly loaded from the DB, then sort them with
Array#sort!.Adding a note to this, if you didn’t want to use the
created_atattribute for your sort condition, all you would need to do is ensure that bothPhotoandTaskhave some attribute with a common name, such asdate_addedor whatever. As long as there is something with a common name to sort by, you’re good to go.