Ruby Rails 3.2如何通过属性数组的哈希来group_by?

时间:2013-07-30 20:46:52

标签: ruby ruby-on-rails-3 group-by enumerable

我有一个带有属性found_in的模型缺陷。我有一个哈希test_phases,其键是各种测试阶段,其值是一个found_in值的数组。有没有办法通过test_phases对缺陷进行分组?比如Defect.group_by(?test_phases)?。

我正在使用的代码是丑陋的

defects = {}
test_phases.each do |test_phase, found_ins|
  defects[test_phase] ||= Defect.where(found_in: found_ins].all
end

2 个答案:

答案 0 :(得分:1)

您不需要分组,因为您正在迭代哈希(没有重复的键),输出哈希将不会有按键的多个元素。只需使用map + Hash(或mash作为Facets鉴赏家):

defects = Hash[test_phases.map do |test_phase, found_in_values|
  [test_phase, Defect.where(found_in: found_in_values)]
end]

答案 1 :(得分:0)

我通过使用连接表DefectFound

创建TestPhase模型来解决这个问题
test_phase.rb:
    has_many :defect_founds

defect_found.rb:
    belongs_to :test_phase

defect.rb:
    belongs_to :defect_found, foreign_key: :found_in, primary_key: :name # defect_found.name = defect.found_in
    has_one :test_phase, through: :defect_found

controller:
    @defects = Defect.includes(:test_phase).select('found_in, COUNT(id) as backlog').group(:found_in).group_by(&:test_phase)

view:
    %table
      - @defects.each do |test_phase, backlogs|
        %tr
          %td= test_phase.name if test_phase.present?
          %td= backlogs.map(&:backlog).inject(:+)