Skip to content

Commit 1c8272a

Browse files
committed
add quantity to cart_items
1 parent 9cf6e97 commit 1c8272a

4 files changed

Lines changed: 12 additions & 3 deletions

File tree

app/controllers/products_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def add_to_cart
1414
@product = Product.find(params[:id])
1515

1616
if !current_cart.items.include?(@product)
17-
current_cart.add_product_to_cart(@product)
17+
current_cart.add_product_to_cart(@product, 1)
1818
flash[:notice] = "你已成功將 #{@product.title} 加入購物車"
1919
else
2020
flash[:warning] = "你的購物車內已有此物品"

app/models/cart.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ class Cart < ActiveRecord::Base
1414

1515

1616
def add_product_to_cart(product)
17-
items << product
17+
cart_item = cart_items.build
18+
cart_item.product = product
19+
cart_item.quantity = amount
20+
cart_item.save
1821
end
1922

2023
def total_price
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class AddQuantityToCartItem < ActiveRecord::Migration
2+
def change
3+
add_column :cart_items, :quantity,:integer, :default => 1
4+
end
5+
end

db/schema.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,14 @@
1111
#
1212
# It's strongly recommended that you check this file into your version control system.
1313

14-
ActiveRecord::Schema.define(version: 20140613065223) do
14+
ActiveRecord::Schema.define(version: 20140619164232) do
1515

1616
create_table "cart_items", force: true do |t|
1717
t.integer "cart_id"
1818
t.integer "product_id"
1919
t.datetime "created_at"
2020
t.datetime "updated_at"
21+
t.integer "quantity", default: 1
2122
end
2223

2324
create_table "carts", force: true do |t|

0 commit comments

Comments
 (0)