Rails 3. Получить итоги из массива - PullRequest
0 голосов
/ 18 января 2012

Я распечатываю таблицу с итогами строк, но я также хочу получить общий итог столбцов.Следующий код не работает, вместо общих итогов он просто выводит значения последней итерации.

<% @shipments.each do |shipment| %>
  <tr>
    <td style="text-align:center;"><%= shipment.file_number %></td>
    <td><%= shipment.shipper.company_name %></td>
    <td><%= shipment.hbl %></td>
    <td><%= shipment.status %></td>
    <td><%= shipment.age %></td>
    <td><%= shipment.invoice.read_issued_at unless shipment.invoice.nil? %></td>
    <td><%= number_to_currency shipment.invoice.customer_total unless shipment.invoice.nil? %></td>
    <td><%= number_to_currency shipment.invoice.customer_amount_paid unless shipment.invoice.nil? %></td>
    <td><%= number_to_currency shipment.invoice.customer_open_balance unless shipment.invoice.nil? %></td>
  </tr>
  <%
  grand_customer_total = 0
  grand_customer_amount_paid = 0
  grand_customer_open_balance = 0
  grand_customer_total += shipment.invoice.customer_total
  grand_customer_amount_paid += shipment.invoice.customer_amount_paid
  grand_customer_open_balance += shipment.invoice.customer_open_balance
  %>
  <% if @shipments.last == shipment %>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <th>Totals</th>
    <td><%= number_to_currency grand_customer_total %></td>
    <td><%= number_to_currency grand_customer_amount_paid %></td>
    <td><%= number_to_currency grand_customer_open_balance %></td>
  </tr>
  <% end %>

Ответы [ 4 ]

2 голосов
/ 18 января 2012

Причина, по которой ваш код не работает, состоит в том, что ваши переменные определены в блоке, поэтому они считаются локальными переменными блока.После выхода из блока эти переменные помечаются как очищенные;каждая итерация переопределяет эти переменные.Также не помогает, что вы переназначаете их на 0 на каждой итерации, но это даже не вступает в силу здесь, потому что переменные не определяются каждый раз.

Вы можете просто определитьпеременные перед блоком, но это все еще довольно грязно.Поскольку в идиомах и соглашениях Ruby акцент делается на чистый и хорошо организованный код, я бы отошел от этого и вместо этого вычислял эти числа отдельно, возможно, в вашем контроллере.1006 * для сравнения, вы можете просто сделать следующее после вывода таблицы поставок:

<tr>
  <td colspan="5"></td>
  <th>Totals</th>
  <td><%= number_to_currency @totals[:overall] %></td>
  <td><%= number_to_currency @totals[:paid] %></td>
  <td><%= number_to_currency @totals[:balance] %></td>
</tr>
2 голосов
/ 18 января 2012

Вы устанавливаете общий итог на ноль каждый раз через цикл.переместить инициализацию вверх перед циклом.

1 голос
/ 18 января 2012
<%
grand_customer_total = 0
grand_customer_amount_paid = 0
grand_customer_open_balance = 0
%>  
<% @shipments.each do |shipment| %>
<tr>
  <td style="text-align:center;"><%= shipment.file_number %></td>
  <td><%= shipment.shipper.company_name %></td>
  <td><%= shipment.hbl %></td>
  <td><%= shipment.status %></td>
  <td><%= shipment.age %></td>
  <td><%= shipment.invoice.read_issued_at unless shipment.invoice.nil? %></td>
  <td><%= number_to_currency shipment.invoice.customer_total unless shipment.invoice.nil? %></td>
  <td><%= number_to_currency shipment.invoice.customer_amount_paid unless shipment.invoice.nil? %></td>
  <td><%= number_to_currency shipment.invoice.customer_open_balance unless shipment.invoice.nil? %></td>
</tr>
<%
grand_customer_total += shipment.invoice.customer_total
grand_customer_amount_paid += shipment.invoice.customer_amount_paid
grand_customer_open_balance += shipment.invoice.customer_open_balance
%>
<% if @shipments.last == shipment %>
<tr>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <td></td>
  <th>Totals</th>
  <td><%= number_to_currency grand_customer_total %></td>
  <td><%= number_to_currency grand_customer_amount_paid %></td>
  <td><%= number_to_currency grand_customer_open_balance %></td>
</tr>
<% end %>
1 голос
/ 18 января 2012

вы можете использовать ruby ​​inject

что-то вроде

@shipments.inject(0) { |sum, shipment| sum + shipment.invoice.customer_total }

или чтобы не нарушать компоновку вашего кода, просто инициализируйте объекты grand_customer_* вне цикла @shipments.each, потому чтовы сбрасываете их каждый раз через

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...