按列对ActiveRecord对象数组进行排序

时间:2021-09-18 13:27:09

I need to sort an array of ActiveRecord objects by the value in one of the columns but am unsure of how to do this.

我需要通过其中一列中的值对ActiveRecord对象数组进行排序,但我不确定如何执行此操作。

Example, I have an Schedule model that has a Duration column. I then have two arrays of Schedule objects OriginalList and NewList. I want to sort each of those lists by Duration. I think that I'm looking for something like: -

例如,我有一个Schedule模型,它有一个Duration列。然后我有两个Schedule对象OriginalList和NewList数组。我想按持续时间对每个列表进行排序。我想我正在寻找类似的东西: -

Schedule.find(:all, 
              :conditions => "schedule_id IN (select schedule_id from 
                                              #{array.each.schedule_id}",
              :order => 'duration')

However, this doesn't look right at all! Not even in SQL!!

但是,这看起来并不正确!甚至不在SQL !!

Any hints on how to do this would be appreciated.

任何关于如何做到这一点的提示将不胜感激。

1 个解决方案

#1


Oops. Ignore that! By writing it down I figured out what I actually wanted to do.

哎呀。忽略那个!通过写下来,我想出了我真正想做的事情。

Schedule.find(:all, :conditions => "schedule_id in ("1", "2", "3"), :order => "duration")

where the 1, 2, 3 can be generated from the array prior to calling.

在调用之前可以从阵列生成1,2,3。

Blame it on Friday afternoon! :D

星期五下午归咎于它! :d

#1


Oops. Ignore that! By writing it down I figured out what I actually wanted to do.

哎呀。忽略那个!通过写下来,我想出了我真正想做的事情。

Schedule.find(:all, :conditions => "schedule_id in ("1", "2", "3"), :order => "duration")

where the 1, 2, 3 can be generated from the array prior to calling.

在调用之前可以从阵列生成1,2,3。

Blame it on Friday afternoon! :D

星期五下午归咎于它! :d