I used group_by to get a certain desired result. Based on the explanation in the answer, I have updated my question to reflect the answer, to see the steps it took to arrive at a solution, see the edit history.
@grouped_test_specific_reports = TestSpecificReport.all.group_by(&:equipment_type_name)
The code above produced this result:
2.5.1 :026 > pp @grouped_test_specific_reports
{"Ultrasonic Probes"=>
[#<TestSpecificReport:0x00007f832aa2d6e0
id: 10,
equipment_type_id: 2,
test_method_id: 1,
equipment_amount: "Multiple",
equipment_heading: "UT Probes">],
"Ultrasonic Instruments"=>
[#<TestSpecificReport:0x00007f832aa2d3c0
id: 8,
equipment_type_id: 1,
test_method_id: 1,
equipment_amount: "Single",
equipment_heading: "UT Instrument">],
"Visual Test Equipment"=>
[#<TestSpecificReport:0x00007f832aa2cfb0
id: 11,
equipment_type_id: 4,
test_method_id: 1,
equipment_amount: "Single",
equipment_heading: "VT Equipment">]}
=> {"Ultrasonic Probes"=>[#<TestSpecificReport id: 10, equipment_type_id: 2, test_method_id: 1, equipment_amount: "Multiple", equipment_heading: "UT Probes">], "Ultrasonic Instruments"=>[#<TestSpecificReport id: 8, equipment_type_id: 1, test_method_id: 1, equipment_amount: "Single", equipment_heading: "UT Instrument">], "Visual Test Equipment"=>[#<TestSpecificReport id: 11, equipment_type_id: 4, test_method_id: 1, equipment_amount: "Single", equipment_heading: "VT Equipment">]}
My next goal is to list out the grouped test specific report in the browser by their keys, I was able to do that by @grouped_test_specific_reports.each { |key, value| puts key }
- "Visual Test Equipment"
- "Ultrasonic Instruments" and
- "Ultrasonic Probes"
Now we have to iterate over the values, which happens to be an array, in another loop to be able to compare equipment_amount.
The values with equipment_amount: "Multiple" will have the plus icon in front of them, and the ones with equipment_amount: "Single" will simply be a drop-down:
Here's the code for the UI:
- @grouped_test_specific_reports.each do |equipment_type_name, test_specific_reports|
.form-group.row
.col-sm-6
%label
= equipment_type_name
= select_tag '', options_from_collection_for_select(test_specific_reports, :id, :equipment_heading), { include_blank: "Select #{equipment_type_name} List", class: 'form-control select2', style: 'width: 100%;' }
.col-sm-1
- test_specific_reports.each do |test_specific_report|
- if test_specific_report.equipment_amount == 'Multiple'
.icon.text-center
%i.fa.fa-plus-circle.add-icon