按多列对活动记录数组进行排序

时间:2015-01-15 23:33:22

标签: ruby ruby-on-rails-3

给定一系列活动记录

jobs = [#<Job _id: 1, created_at: 2014-07-15 19:18:40 UTC, organization: "Acme In.c">,
        #<Job _id: 3, created_at: 2014-05-20 09:27:38 UTC, organization: "Baxter">, 
        #<Job _id: 2, created_at: 2014-11-25 12:21:00 UTC, organization: "Wizard">, 
        #<Job _id: 3, created_at: 2015-01-15 07:20:10 UTC, organization: "Baxter">]

我如何先按organization按升序排序A-> Z,然后按created_at降序排列,以此结束...

jobs = [#<Job _id: 1, created_at: 2014-07-15 19:18:40 UTC, organization: "Acme In.c">,
        #<Job _id: 3, created_at: 2015-01-15 07:20:10 UTC, organization: "Baxter">,
        #<Job _id: 3, created_at: 2014-05-20 09:27:38 UTC, organization: "Baxter">,
        #<Job _id: 2, created_at: 2014-11-25 12:21:00 UTC, organization: "Wizard">]

我试图做jobs.sort_by{|j| [j.organization, j.created_at]}但是我不确定如何指定多个asc / desc规则,而我得到的最接近的规则按组织排序但是按创建排序给我最老的最新而不是最新到最旧。我也尝试先分组然后排序,但我也无法让它工作。任何帮助,如果感激。

2 个答案:

答案 0 :(得分:3)

一个好方法是像这样使用sort<=>以及nonzero?

jobs.sort{|a,b| 
  (a.organization <=> b.organization).nonzero? ||
  (b.created_at <=> a.created_at)
}

此代码说:

  1. 按组织比较A和B.
  2. 如果他们不同,那么我们就有答案。
  3. 如果它们相同,那么我们需要做更多。
  4. 按时间比较B和A. (注意B&amp; A的顺序相反)
  5. 如果他们不同,那么我们就有答案。
  6. 如果它们相同,那么排序顺序并不重要。 (Ruby排序是&#34;不稳定&#34;)
  7. 独立于ActiveRecord的示例代码:

    require 'time'
    require 'ostruct'
    
    jobs = [
      OpenStruct.new(_id: 1, created_at: Time.parse("2014-07-15 19:18:40 UTC"), organization: "Acme Inc"),
      OpenStruct.new(_id: 3, created_at: Time.parse("2014-05-20 09:27:38 UTC"), organization: "Baxter"), 
      OpenStruct.new(_id: 2, created_at: Time.parse("2014-11-25 12:21:00 UTC"), organization: "Wizard"), 
      OpenStruct.new(_id: 3, created_at: Time.parse("2015-01-15 07:20:10 UTC"), organization: "Baxter")
    ]
    

答案 1 :(得分:0)

中所述
  

http://guides.rubyonrails.org/active_record_querying.html

尝试jobs.order("organization ASC", "created_at DESC")或以下

jobs.order("organization ASC").order("created_at DESC")