使用相应模型中的方法对哈希进行排序

假设您有一个具有属性“age”的模型Dog,这是一种确定“吠叫频率”的方法:

class Dog  { order('age ASC') } def barking_frequency # some code end end 

在您的控制器中,您有:

 def index @dogs = Dog.by_age end 

一旦你有@dogs的哈希值,你如何通过barking_frequency对它进行排序,这样结果就可以将特定年龄的狗排在一起,如下所示:

 Name Age Barking Frequency Molly 2 1 Buster 2 4 Jackie 2 7 Dirk 3 1 Hank 3 3 Jake 3 4 Spot 10 0 

以下将工作:

 def index @dogs = Dog.by_age.sort_by { |dog| [dog.age, dog.barking_frequency] } end