问题
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
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
回答1:
Below will work:
def index
@dogs = Dog.by_age.sort_by { |dog| [dog.age, dog.barking_frequency] }
end
来源:https://stackoverflow.com/questions/25919677/sorting-a-hash-using-a-method-from-the-corresponding-model