简体   繁体   English

具有关联的多级排序

[英]Multi level sort with associations

My setup: Rails 3.0.9, Ruby 1.9.2 我的设置: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). 我需要的是能够返回首先按项目名称(ASC)排序的结果集,然后交织按日期排序(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. 我更喜欢从ActiveRecord获取整个结果集,然后在Ruby中对其进行排序,但是不确定如何进行处理,任何见解将不胜感激。 Thanks. 谢谢。

How about something like this? 这样的事情怎么样? Grab all the objects, eagerly loaded from the DB, then sort them with Array#sort! 抢先从数据库急切加载的所有对象,然后使用Array#sort!对它们进行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. 对此添加注释,如果您不想将created_at属性用于排序条件,那么您要做的就是确保PhotoTask都具有一些具有通用名称的属性,例如date_added或其他名称。 As long as there is something with a common name to sort by, you're good to go. 只要有一个通用名称可以排序,您就可以进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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