[英]Multi level sort with associations
我的設置:Rails 3.0.9,Ruby 1.9.2
這是我的模特
class Project
has_many :tasks
has_many :photos
class Task
belongs_to :project
class Photos
belongs_to :project
我需要的是能夠返回首先按項目名稱(ASC)排序的結果集,然后交織按日期排序(DESC)的任務和照片。 這是我需要的訂單的示例輸出
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)
我更喜歡從ActiveRecord獲取整個結果集,然后在Ruby中對其進行排序,但是不確定如何進行處理,任何見解將不勝感激。 謝謝。
這樣的事情怎么樣? 搶先從數據庫急切加載的所有對象,然后使用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
對此添加注釋,如果您不想將created_at
屬性用於排序條件,那么您要做的就是確保Photo
和Task
都具有一些具有通用名稱的屬性,例如date_added
或其他名稱。 只要有一個通用名稱可以排序,您就可以進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.