我正在建設E商店的鐵路。我正在嘗試從購物車中移除商品,但我不確定我會如何做到這一點。我不確定是否應該開始,因爲我是一個完全noob,並且一直在遵循一個教程,其中不包括如何添加刪除功能的項目。從購物車導軌應用程序中刪除項目?
這裏是GitHub庫github.com/DadiHall/brainstore
誰能告訴我這裏的鏈接?
我迄今是
的routes.rb
resource :cart, only: [:show] do
post "add", path: "add/:id", on: :member
delete "remove", path: "destroy/:id", on: :member
get :checkout
end
在carts_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
#Delete
def destroy
redirect_to cart_path
end
end
的意見/車/ show.html.erb
<% @cart.items.each do |item| %>
<tr>
<td><%= item.quantity %></td>
<td><%= image_tag item.product.image.thumb %><%= link_to item.product.name, item.product %></td>
<td><%= item.total_price %></td>
<td><%= link_to 'Empty Cart', cart_path(@cart), method: :delete, confirm: 'are you sure?' %>
</td>
</tr>
<% end %>
cart.rb model
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
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
end
你可以分享教程或你的代碼嗎? – Saad
嗨,這裏是教程的鏈接,我註冊了免費試用版https://code.tutsplus.com/courses/build-a-store-with-a-payment-gateway-in-rails – DaudiHell
我沒有有機會獲得這門課程,讓你在github上分享你的代碼,以便我可以看看。 – Saad