在 rails 上清空购物车 ruby

Clear cart ruby on rails

我是 Ruby rails 的初学者,我正在尝试创建一个小型购物车系统。多亏了 stackoverflox 和网络上的一些小教程,我已经相当进步了。 问题是我不能毫无错误地清空我的购物车,我必须创建一个从我的应用程序中删除 cookie 的操作,但我不能。这是我的应用程序的来源,可以使用但无法清空购物篮

view/cart/index.html.erb

>         <h1>Votre panier</h1>
>     <!DOCTYPE html>
>     <html>
>     <head>
>       <title></title>
>     </head>
>     <body>
>     
>     <% total = 0 %>
>     
>     <table>
>       <% @cart.each do |id, quantity| %>
>       <% item = Item.find(id) %>
>       <tr>
>           <td class="images"><%= link_to image_tag(item.image_url, :size => "50x50"), item %></td>
>           <td width="160"><%= item.produit %></td>
>           <td width="160"><%= quantity %></td>
>           <td width="160"><%= number_to_currency(item.prix, unit: "€") %></td>
>           </tr>
>           <% total += quantity * item.prix %>
>     
>           <% end %>
>     
>           <tr>
>               <td colspan="4">Total :</td>
>               <td><%= number_to_currency(total, unit: "€") %></td>
>           </tr>
>       
>     </table>
>
>       # Please, i want empty my cart !
>       <%= link_to 'Back', items_path %>
>     
>     </body>
>     </html>

cart_controller.rb

class CartController < ApplicationController
  def index
    @cart = session[:cart] || {}
  end

  def add
    id = params[:id]
    cart = session[:cart] ||= {}
    cart[id] = (cart[id] || 0) + 1

    redirect_to :action => :index

  end


end

routes.rb

Rails.application.routes.draw do

resources :items      

get 'cart/index'

match ':controller/:action/:id', via: [:get, :post]

root :to => "items#index"

end

您可以随时从会话哈希中删除任何 "key",方法是:

session.delete(key)

你的情况:

session.delete(:cart)

如果您想在点击 "Back" 时执行此操作,则需要将其添加到该路由路径的控制器操作中。