2

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
Kevin K
  • 2,191
  • 2
  • 28
  • 41

1 Answers1

2

Below will work:

def index
  @dogs = Dog.by_age.sort_by { |dog| [dog.age, dog.barking_frequency] }
end
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317