使用来自相应模型的方法对散列进行排序

使用来自相应模型的方法对散列进行排序

问题描述:

假设你有一个模型Dog,其属性为年龄,它决定了吠叫频率:

Let's say you have a model Dog with an attribute "age" a method that determines "barking frequency":

class Dog < ActiveRecord::Base
  scope by_age, -> { order('age ASC') }

  def barking_frequency
    # some code
  end
end

在你的控制器中你有:

In your controller you have:

def index
  @dogs = Dog.by_age
end

一旦您拥有@dogs的哈希值,你怎么能通过barking_frequency对它进行排序,以便结果保持特定年龄段的狗一起排序,如下所示:

Once you have the hash for @dogs, how can you sort it by barking_frequency, so that the result keeps the dogs of a particular age sorted together, like this:

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


b
$ b

Below will work:

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