【发布时间】:2016-11-06 17:00:45
【问题描述】:
我正在开发一个电子商务应用程序,当用户将产品添加到购物车时,我不知道如何更新产品库存数量。 因为我是一个新手,所以我对这个应用程序的大部分内容都遵循了教程。但是本教程并没有介绍当用户将产品添加到购物车时如何更新产品库存数量。
到目前为止,我已经将此方法添加到 cart.rbmodel
def upd_quantity
if cart.purchased_at
product.decrement!(quantity: params[:stock_quantity])
end
end
但我真的被困住了,不知道自己在做什么 如果有人可以看看这个并建议我如何在应用程序中实现这个功能,那就太好了。
这里是github repo的链接https://github.com/DadiHall/brainstore
这是我目前拥有的。
cart_item.rb型号
class CartItem
attr_reader :product_id, :quantity
def initialize product_id, quantity = 1
@product_id = product_id
@quantity = quantity
end
def increment
@quantity = @quantity + 1
end
def product
Product.find product_id
end
def total_price
product.price * quantity
end
def upd_quantity
if cart.purchased_at
product.decrement!(quantity: params[:stock_quantity])
end
end
end
cart.rbmodel
class Cart
attr_reader :items
def self.build_from_hash hash
items = if hash ["cart"] then
hash["cart"] ["items"].map do |item_data|
CartItem.new item_data["product_id"], item_data["quantity"]
end
else
[]
end
new items
end
def initialize items = []
@items = items
end
def add_item product_id
item = @items.find { |item| item.product_id == product_id }
if item
item.increment
else
@items << CartItem.new(product_id)
end
end
def empty?
@items.empty?
end
def count
@items.length
end
def serialize
items = @items.map do |item|
{
"product_id" => item.product_id,
"quantity" => item.quantity
}
end
{
"items" => items
}
end
def total_price
@items.inject(0) { |sum, item| sum + item.total_price }
end
end
product.rb型号
class Product < ActiveRecord::Base
mount_uploader :image, ImageUploader
validates_presence_of :name, :price, :stock_quantity
validates_numericality_of :price, :stock_quantity
belongs_to :designer
belongs_to :category
belongs_to :page
def self.search(query)
where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%")
end
end
`cart_controller.rb`
class CartsController < ApplicationController
before_filter :initialize_cart
def add
@cart.add_item params[:id]
session["cart"] = @cart.serialize
product = Product.find params[:id]
redirect_to :back, notice: "Added #{product.name} to cart."
end
def show
end
def checkout
@order_form = OrderForm.new user: User.new
@client_token = Braintree::ClientToken.generate
end
def remove
cart = session['cart']
item = cart['items'].find { |item| item['product_id'] == params[:id] }
if item
cart['items'].delete item
end
redirect_to cart_path
end
end
【问题讨论】:
标签: ruby-on-rails ruby e-commerce shopping-cart