user2967603 user2967603 - 1 year ago 64
HTML Question

Display values from two hash's in a single html table

I'm trying to create a table in one of my views that displays a combination of values from two separate hash's in a single row. The desired output would have three columns: Material, Units and Net Weight.

In my controller I generate the hashes like so:

@materialGroups = @shipment.shipmentDetails.count(:group => :product_name)
@materialTotals =

@materialGroups contains the product_name and a count of number of units for each product
@materialTotals contains the product_name and a sum of the net_weights for each product.

My view contains the following code to display the table:

<table class="table">
<th>Net Weight</th>

<% @materialGroups.each do | product_name, count| %>
<% @materialTotals.each do | ship_net_weight, sum | %>
<td><%= product_name %></td>
<td nowrap="true"><%= number_with_delimiter(count) %></td>
<td nowrap="true"><%= number_with_delimiter(sum) %> lbs</td>
<% end %>
<% end %>

This all works fine as long as only one product_name group is returned (ie. Only Steel was in ShipmentDetails). However if I have more than one product_name (ie. Steel and Copper) in ShipmentDetails for a Shipment, I get duplicate rows in the table for each product_name. So instead of having one row for Steel with 20 Units @ a net weight of 200 lbs, I get two identical rows. And two identical rows for Copper.

How can either:

  1. Iterate over the two hash's correctly in the view?

  2. Or alternately, generate just one hash and iterate over it for the desired result?

Answer Source

If you use select you can produce one hash to loop over. Try:

@materials ="count(*), sum(net_weight), product_name").group(:product_name)

Then in your view you can do something like:

<% @materials.each do |m| %>
    <td><%= m.product_name %></td>
    <td nowrap="true"><%= number_with_delimiter(m.count) %></td>  
    <td nowrap="true"><%= number_with_delimiter(m.sum) %> lbs</td>
<% end %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download