我正在尝试创建一个像这样的二维数组......
@transactions = {}
@expenses.each do |expense|
@transactions[expense.id.to_s + '-expense'] = {'identifier' => expense.id.to_s + '-expense', 'id' => expense.id, 'type' => 'expense', 'issued_on' => expense.issued_on, 'amount' => expense.amount}
end
@invoices.each do |invoice|
@transactions[invoice.id.to_s + '-invoice'] = {'identifier' => invoice.id.to_s + '-invoice', 'id' => invoice.id, 'type' => 'invoice', 'issued_on' => invoice.issued_on, 'amount' => invoice.total}
end
但是当我遍历数组来创建行时,它首先给出了键,然后是整个数组......
- 1-expense
- identifier: 1-expense
id: 1
type: expense
issued_on: 2012-05-03
amount: 8.99
---
- 2-expense
- identifier: 2-expense
id: 2
type: expense
issued_on: 2012-05-25
amount: 4.96
---
- 3-expense
- identifier: 3-expense
id: 3
type: expense
issued_on: 2012-05-01
amount: 56.08
我迭代创建行(当然,我应该做像transaction.id或transaction.issued_on这样的东西,但我调试,所以你可以看到我的意思)......
<% @transactions.each do |transaction| %>
<tr class="<%= cycle("odd", "even") %>">
<td>
<%= debug transaction %>
</td>
<td></td>
<td></td>
<td></td>
</tr>
<% end %>
所以我最终得到了这样一张桌子......
| 1-expense |
| identifier: 1-expense, id: 1, type: expense, issued_on: 2012-05-03, amount: 8.99 |
| 2-expense |
| identifier: 2-expense, id: 2, type: expense, issued_on: 2012-05-25, amount: 4.96 |
| 3-expense |
| identifier: 3-expense, id: 3, type: expense, issued_on: 2012-05-01, amount: 56.08 |
当我的桌子应该看起来像这样
| identifier: 1-expense, id: 1, type: expense, issued_on: 2012-05-03, amount: 8.99 |
| identifier: 2-expense, id: 2, type: expense, issued_on: 2012-05-25, amount: 4.96 |
| identifier: 3-expense, id: 3, type: expense, issued_on: 2012-05-01, amount: 56.08 |
我不知道如何创建一个包含事务数据行的简单表,而不是那些带有哈希键的额外行。
答案 0 :(得分:4)
您已使用{}
语法创建了哈希,而不是数组。
如果你想迭代哈希的值(没有键),你可以这样做:
<% @transactions.each_value do |transaction| %>
...
或者,您可以使用数组来保存行:
@transactions = []
@expenses.each do |expense|
@transactions << {'identifier' => expense.id.to_s + '-expense', 'id' => expense.id, 'type' => 'expense', 'issued_on' => expense.issued_on, 'amount' => expense.amount}
end
@invoices.each do |invoice|
@transactions << {'identifier' => invoice.id.to_s + '-invoice', 'id' => invoice.id, 'type' => 'invoice', 'issued_on' => invoice.issued_on, 'amount' => invoice.total}
end
然后您现有的erb模板应该更好。