2014-01-09 23 views
1

我一直在關注使用Rails 4進行敏捷Web開發的書,並且已經完成了第10章 - 整理購物車。在購物車中未正確添加Rails 4行項目的敏捷web開發

到目前爲止,一切都一直很好,直到我更新購物車,以顯示單個項目和整個購物車的總價格。

這裏是發生了什麼快照:

Current Cart Output

顯然,價格應該呈現出作爲一個整體,而不是並排。

這是我的觀點:

<% if notice %> 
<p id="notice"><%= notice %></p> 
<% end %> 

<h2>Your Cart</h2> 
<table> 

<% @cart.line_items.each do |item| %> 

<tr> 
<td><%= item.quantity %>&times;</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; 
} 
} 

我希望有一個簡單的解決方案,以及任何幫助將非常感激。

謝謝...

+0

這可能是一些事情,但我們沒有足夠的信息來確定。您可能在數據庫中有重複項,或者以某種方式爲第一項創建一組值。表單中的輸出看起來像一個數組如何表示。數據庫中有什麼? –

+0

數據庫是SQLite。購物車工作的很好,它只需要列出各個產品和定價,但是當我使用上面的代碼更新它時,它開始顯示錯誤。我一直跟着這本書,所以我不期待這種類型的錯誤。我不認爲它在數據庫中是重複的,因爲我目前只有兩個條目。 –

回答

1

注意,總價格爲車是總價格爲您行字符串連接項目,而不是他們的數字總和。

您的第一個訂單項的總價格是「5.99」和「5.99」的字符串連接。

看起來您可能會將價格存儲爲字符串而不是十進制值。

爲了說明問題,

>> ["4.95", "5.95"].sum 
=> "4.955.95" 

檢查schema.rb,並確保您有它的此項:

create_table "products", force: true do |t| 
    t.string "title" 
    t.text  "description" 
    t.string "image_url" 
    t.decimal "price",  precision: 8, scale: 2 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

相反,如果你有

t.string "price" 

你必須修改那個。

正確的方法是使用新的遷移*。在命令行中,發出

rails g migration change_data_type_for_price 

,並在生成的遷移文件添加

change_column :products, :price, :decimal, precision: 8, scale: 2 

然後運行rake db:migrate,你應該是好去。

*此外,由於這是一個小型項目,您可以編輯原始遷移文件,刪除數據庫,然後再次運行所有遷移並重新種子,但這不是最佳實踐方法。

+1

非常感謝你的回答,你剛剛度過了我的一天!我確實把我的字符串設置爲一個字符串,而不是一個小數,這是在項目的開始階段,所以我從來沒有想過要檢查。優秀的答案... –

+0

按照你的指示,它現在完美地工作! –

1

你可以嘗試

line_items.collect(&:total_price).sum 

,而不是

line_items.to_a.sum { |item| item.total_price } 
+0

感謝您的答覆 - 只是嘗試了您的建議,並沒有改變輸出,數字仍然並排。 –

+0

@TonyStaunton你熟悉調試器嗎? – arun15thmay