Skip to content

Commit

Permalink
items can be deleted from a cart
Browse files Browse the repository at this point in the history
  • Loading branch information
Derrick Fonseca committed Nov 19, 2024
1 parent 711770e commit f9da274
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
12 changes: 8 additions & 4 deletions app/controllers/carts_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ def add_item
end


# Remove an item from the cart
# Remove an item from the cart but also have a rescue if for some reason it cant be found or destroyed
def remove_item
cart_item = CartItem.find(params[:id])
cart_item.destroy
redirect_to @cart, notice: "Item removed from cart."
cart_item = CartItem.find_by(id: params[:id])
if cart_item
cart_item.destroy
redirect_to cart_path(params[:cart_id]), notice: "#{cart_item.item.name} was removed from the cart."
else
redirect_to cart_path(params[:cart_id]), alert: "Item not found in the cart."
end
end

private
Expand Down
3 changes: 3 additions & 0 deletions app/views/carts/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
<td><%= number_to_currency(cart_item.total_price) %></td>
<td><%= number_to_currency(cart_item.discount) %></td>
<td><%= number_to_currency(cart_item.total_price - cart_item.discount) %></td>
<td>
<%= button_to 'Remove', remove_item_cart_path(@cart.id, id: cart_item.id), method: :delete, data: { confirm: 'Are you sure you want to remove this item?' } %>
</td>
</tr>
<% end %>
</tbody>
Expand Down
13 changes: 8 additions & 5 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,26 @@
resources :promotions
resources :items
resources :categories

# Cart routes
resources :carts, only: [ :show ] do
member do
post "add_item"
delete "remove_item/:id", to: "carts#remove_item", as: "remove_item"
end
end

# Dedicated route for removing items from the cart
delete "carts/:cart_id/remove_item/:id", to: "carts#remove_item", as: "remove_item_cart"

# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
# Health check route
get "up" => "rails/health#show", as: :rails_health_check

# Render dynamic PWA files from app/views/pwa/*
# PWA support
get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker
get "manifest" => "rails/pwa#manifest", as: :pwa_manifest

# Defines the root path route ("/")
# Root path
# root "posts#index"
end

0 comments on commit f9da274

Please sign in to comment.