我一直在關注使用Rails 4進行敏捷Web開發的書,並且已經完成了第10章 - 整理購物車。在購物車中未正確添加Rails 4行項目的敏捷web開發
到目前爲止,一切都一直很好,直到我更新購物車,以顯示單個項目和整個購物車的總價格。
這裏是發生了什麼快照:
顯然,價格應該呈現出作爲一個整體,而不是並排。
這是我的觀點:
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h2>Your Cart</h2>
<table>
<% @cart.line_items.each do |item| %>
<tr>
<td><%= item.quantity %>×</td>
<td><%= item.product.title %></td>
<td class="item_price"><%= number_to_currency(item.total_price) %></td>
</tr>
<% end %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to 'Empty cart', @cart, method: :delete,
data: { confirm: 'Are you sure?' } %>
這裏是我的LINE_ITEM型號:
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
def total_price
product.price * quantity
end
end
這是我的車型號:
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_product(product_id)
current_item = line_items.find_by(product_id: product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(product_id: product_id)
end
current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
end
這裏是造型:
.carts {
.item_price, .total_line {
text-align: right;
}
.total_line .total_cell {
font-weight: bold;
border-top: 1px solid #595;
}
}
我希望有一個簡單的解決方案,以及任何幫助將非常感激。
謝謝...
這可能是一些事情,但我們沒有足夠的信息來確定。您可能在數據庫中有重複項,或者以某種方式爲第一項創建一組值。表單中的輸出看起來像一個數組如何表示。數據庫中有什麼? –
數據庫是SQLite。購物車工作的很好,它只需要列出各個產品和定價,但是當我使用上面的代碼更新它時,它開始顯示錯誤。我一直跟着這本書,所以我不期待這種類型的錯誤。我不認爲它在數據庫中是重複的,因爲我目前只有兩個條目。 –