我在使用 Kaminari Gem 进行分页时遇到问题,我想计算应用程序中所有费用的总和,但是,在我看来,我只能获得当前查看的单个分页页面的总费用。如何计算所有分页页面的总费用?
在我的控制器中
def index
@expenses = Expense.order(:batch_id).page(params[:page])
@total_expenses = @expenses.map(&:total).sum
end
在我的模型中,我已经分配了我想要的每页
class Expense < ApplicationRecord
belongs_to :batch
paginates_per 10
def total
unit_price.to_i * quantity.to_i
end
end
在我看来
<div>
<table>
<thead>
<tr>
<th></th>
<th>Batch No.</th>
<th>Date</th>
<th>Category</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total Expense</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<% @expenses.each do |expense| %>
<tr>
<td>
<div>
<input id="checkbox-table-search-1">
<label for="checkbox-table-search-1">checkbox</label>
</div>
</td>
<th><%= expense.batch.batch_no %></th>
<td><%= expense.date.strftime('%d %b %Y') %></td>
<td><%= expense.category %></td>
<td><%= expense.quantity %></td>
<td><%= expense.unit_price %></td>
<td><%= number_to_currency(expense.total, :unit => "") %></td>
<td><%= expense.description %></td>
<td><%= link_to "Show", expense %>
<%= link_to 'Edit', edit_expense_path(expense) %>
<%= link_to 'Destroy', expense, data: { turbo_method: "delete", turbo_confirm: 'Are you sure?' }%>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<div>
Total Expense per page = <%= number_to_currency(@total_expenses, :unit => "Tshs. ", :delimiter => ",") %>
</div>
<div>
<%= paginate @expenses %>
</div>
我更喜欢使用 SQL
sum
。您可以在这里阅读更多内容。使用 map
,所有记录都必须在计算之前加载到内存中。
# you can also group, or adding conditions before calculation
@total_expenses = Expense.sum("unit_price*quantity")
# or
@total_expenses = Expense.group("category").sum("unit_price*quantity")