diff --git a/app/controllers/carts_controller.rb b/app/controllers/carts_controller.rb
index 7b0507f..e0a968f 100644
--- a/app/controllers/carts_controller.rb
+++ b/app/controllers/carts_controller.rb
@@ -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
diff --git a/app/views/carts/show.html.erb b/app/views/carts/show.html.erb
index a38b958..18c0c64 100644
--- a/app/views/carts/show.html.erb
+++ b/app/views/carts/show.html.erb
@@ -21,6 +21,9 @@
<%= number_to_currency(cart_item.total_price) %> |
<%= number_to_currency(cart_item.discount) %> |
<%= number_to_currency(cart_item.total_price - cart_item.discount) %> |
+
+ <%= 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?' } %>
+ |
<% end %>
diff --git a/config/routes.rb b/config/routes.rb
index 278258d..80c200f 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -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