我可以在模型中使用两个group_by吗?

时间:2017-03-25 17:01:41

标签: ruby-on-rails

 class << self
   def category_sort
     order(small_category_id: "asc", id: "asc")
     .group_by { |w| w.small_category.name }
   end
 end

这是当前的代码,我可以像这样得到哈希。

 small_category1 => [data1,data2,data3]
 small_category2 => [data4,data5]
 small_category3 => [data6,data7,data8]

是否可以在模型中使用两个group_by?我不知道如何编写程序。我有big_category所以我想像这样创建哈希。

 big_category1 => small_category1 => [data1,data2,data3]
               => small_category2 => [data4,data5]
 big_category2 => small_category3 => [data6,data7,data8]

目前我可以像这样获得上述表格。

 class << self
   def category_sort
     r = order(small_category_id: "asc", id: "asc")
         .group_by { |w| [w.small_category.big_category.name, w.small_category.name] }

     hash = Hash.new { |h,k| h[k] = {} }
     r.each do |k, v|
       hash[k[0]][k[1]] = v
     end
   end
 end

有更聪明的方法吗?

2 个答案:

答案 0 :(得分:0)

如果您想在一行中编写相同的逻辑以使其看起来更清晰:

class << self
   def category_sort
     order(small_category_id: "asc", id: "asc")
     .group_by { |w| [w.small_category.big_category.name, w.small_category.name] }
     .each_with_object(Hash.new { |h,k| h[k] = {} }) {|(k,v),h| h[k.first][k.last] = v}
   end
 end

答案 1 :(得分:0)

嘿,你可以这样试试,

class << self
  def category_sort
    r = order(small_category_id: "asc", id: "asc").group_by { |w| [w.small_category.big_category.name, w.small_category.name] }.map{|key, value| {key.first => {key.last => value}}}.map(&:to_a).reduce(:concat).to_h
  end
end