我正在构建一个发票应用程序,其中发票有许多项目和付款。
在我的索引视图中,我显示了所有发票的列表,其中包括两个虚拟属性:
def total
items.sum { |item| item.total }
end
def balance
self.payments.sum(:amount) - self.total
end
我注意到显示索引视图需要大量的 SQL。是否建议再创建两个表列?到目前为止,我选择不这样做,因为我不喜欢有太多冗余数据。
这是我的控制器:
def index
result = current_user.invoices.includes(:items, :payments)
@invoices = paginate(result)
end
index.html.erb:
<table id="index">
<thead>
<tr>
<th>Number</th>
<th>Date</th>
<th>Total</th>
<th>Balance</th>
<th></th>
</tr>
</thead>
<tbody>
<%= render @invoices %>
</tbody>
</table>
<%= will_paginate @invoices %>
_invoice.html.erb:
<tr>
<td>
<%= link_to invoice.number, invoice_path(invoice) %>
</td>
<td>
<%= l invoice.date %>
</td>
<td>
<%= number_to_currency(invoice.total) %>
</td>
<td>
<%= number_to_currency(invoice.balance) %>
</td>
<td>
<%= destroy_link(invoice) %>
</td>
</tr>
对于索引视图上的每张发票,将生成以下四个 SQL 查询:
(0.1ms) SELECT SUM("payments"."amount") AS sum_id FROM "payments" WHERE "payments"."invoice_id" = 19
CACHE (0.0ms) SELECT "items".* FROM "items" WHERE "items"."invoice_id" = 19
CACHE (0.0ms) SELECT SUM("payments"."amount") AS sum_id FROM "payments" WHERE "payments"."invoice_id" = 19
CACHE (0.0ms) SELECT "items".* FROM "items" WHERE "items"."invoice_id" = 19
(这使得每个索引页有 40 个 SQL 查询。)
我必须承认我对 Rails 比较陌生。所以我想知道是否有最佳实践可以遵循?