0

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

我使用的代码很丑

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

2 回答 2

1

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

defects = Hash[test_phases.map do |test_phase, found_in_values|
  [test_phase, Defect.where(found_in: found_in_values)]
end]
于 2013-07-30T20:55:05.703 回答
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(:+)
于 2013-07-30T23:02:05.513 回答