Sorting a hash using a method from the corresponding model

旧城冷巷雨未停 提交于 2019-12-24 03:16:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!