Daði Hall Daði Hall - 5 months ago 68
Ruby Question

remove item from cart rails app?

I'm building E store in rails. I´m trying to remove Items from the cart but I´m not sure how I would do that. I´m not sure were to start since I'm a total noob and been following a tutorial which doesn't include how to add delete function to the items.

here is a link to github repo

github.com/DadiHall/brainstore


can anyone advise me here?

what I have so far is

routes.rb

resource :cart, only: [:show] do
post "add", path: "add/:id", on: :member
delete "remove", path: "destroy/:id", on: :member

get :checkout
end


in 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


in the views/cart/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 model

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

Answer

In your destroy path in your carts controller you have not destroyed the object yet.

so what you have to do there is

routes.rb

delete 'remove', path: 'destroy/:id'

carts_controller.rb

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

views/carts/show.html.erb

<td><%= link_to 'remove', remove_cart_path(item.product_id), method: :delete %></td>