0

属性 found_in を持つモデルの欠陥があります。キーがさまざまなテスト フェーズで、値が found_in 値の配列であるハッシュ test_phases があります。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
4

2 に答える 2

1

ハッシュを反復しているため(重複キーなし)、グループ化する必要はありません。出力ハッシュにはキーごとに複数の要素が含まれません。map+を使用するだけです (ファセット愛好家のHash場合はマッシュ):

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

I solved this by creating a TestPhase model with a join table DefectFound

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 に答える