使用来自相应模型的方法对散列进行排序 [英] Sorting a hash using a method from the corresponding model

查看:110
本文介绍了使用来自相应模型的方法对散列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个模型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

这篇关于使用来自相应模型的方法对散列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆