我是Ruby on rails的初学者,我正在尝试创建一个小型的购物车系统。感谢stackoverflox和网络上的一些小教程,我已经做得很好了。 问题是我不能没有错误地清空我的购物车,我将不得不创建一个从我的应用程序中删除cookie的操作,但我不能。这是我的应用程序的工作源,但无法清空篮子
查看/购物车/ 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
答案 0 :(得分:1)
您可以删除任何&#34;键&#34;从任何时候的会话哈希,通过做:
session.delete(key)
在你的情况下:
session.delete(:cart)
如果你想在&#34; Back&#34;如果被击中,则需要将其添加到该路径路径的控制器操作中。