我的Transaction
模型包含属性:product_id
,qty
和status
。
我想在状态0,状态1和状态2交易的总qty
的视图中显示所有产品的列表,如下所示:
| Product | Other | buy | Sold | Balance |
--------------------------------------------
| 1 | 12 | 0 | 4 | 8 |
| 2 | 40 | 10 | 18 | 32 |
| 3 | 54 | 14 | 28 | 40 |
我查询(postgresql)上面的结果如下:
SELECT
product_id
,SUM(CASE WHEN status = 0 THEN qty ELSE 0 END) AS Other
,SUM(CASE WHEN status = 1 THEN qty ELSE 0 END) AS Buy
,SUM(CASE WHEN status = 2 THEN qty ELSE 0 END) AS Sold
,(SUM(CASE WHEN status = 0 THEN qty ELSE 0 END) + SUM(CASE WHEN status = 1 THEN qty ELSE 0 END) - SUM(CASE WHEN status = 2 THEN qty ELSE 0 END)) AS Balance
FROM
Transactions
GROUP BY
product_id
ORDER BY
product_id
检查此sqlfiddle以获取查询的测试结果。
这是我目前的代码
def index
@transactions = Transaction.group(:product_id).select(:product_id, "SUM(qty) , :condition => ['status = ?', 0], as other", "SUM(qty) , :condition => ['status = ?', 1], as buy", "SUM(qty) , :condition => ['status = ?', 2], as sold",
"SUM(qty) , :condition => ['status = ?', 0] + SUM(qty) , :condition => ['status = ?', 1] - SUM(qty) , :condition => ['status = ?', 2], as balance").order(:product_id).collect{ |tr| [tr.product_id, tr.other, tr.buy, tr.sold, tr.balance] }
end
和index.html.erb
<table class="data">
<thead>
<tr>
<th>Product_id</th>
<th>Other</th>
<th>Buy</th>
<th>Sold</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<% if @transactions.empty? %>
<tr>
<td colspan="5">not found</td>
</tr>
<% else %>
<% @transactions.each do |(product_id, other, buy, sold, balance), sa| %>
<tr>
<td><%= product_id %></td>
<td><%= other %></td>
<td><%= buy %></td>
<td><%= sold %></td>
<td><%= balance %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
我收到此错误:
ArgumentError in TransactionsController#index
wrong number of arguments (5 for 1)
app/controllers/transactions_controller.rb:10:in `index'
有人可以纠正并帮助我,我显然已经卡住了。