2017-01-12 89 views
0

我有以下四個領域的典範:MySQL的排序按分組日期範圍

scope :active, -> { where("start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}'") } 
scope :ended, -> { where("end_at < '#{Time.now.utc}'") } 
scope :coming_soon, -> { where("start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}'") } 

我希望能夠像做(僞代碼,只是想給一個想法):

Model.all.order(active, coming_soon, ended) 

結果將是該表中的所有行,按滿足active限制的行進行排序,然後是滿足coming_soon限制的行,最後是滿足ended約束條件的行。

回答

1

添加以下的範圍,它似乎已經解決了我的問題:

scope :time_sorted, -> { 
    select("events.*, CASE 
     WHEN start_at <= '#{Time.now.utc}' AND end_at > '#{Time.now.utc}' THEN 1 
     WHEN end_at < '#{Time.now.utc}' THEN 2 
     WHEN start_at > '#{Time.now.utc}' AND start_at < '#{Time.now.utc+6.hours}' THEN 3 ELSE 4 
     END AS formula") 
    .order("formula ASC") 
}