简体   繁体   中英

Multi level sort with associations

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! .

# First, grab all projects and their task/photos from the DB
projects = Project.includes(:tasks, :photos).order("project_name ASC")

# Now, iterate over projects, combine tasks/photos, sort by date
projects.each do |p|
  tasks_and_photos = p.tasks + p.photos
  tasks_and_photos.sort! { |x,y| y.created_at <=> x.created_at }
  # now do something with the tasks and photos!
end

Adding a note to this, if you didn't want to use the created_at attribute for your sort condition, all you would need to do is ensure that both Photo and Task have some attribute with a common name, such as date_added or whatever. As long as there is something with a common name to sort by, you're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM