[英]Ruby on rails: How to ajax cart when change quantity items in cart, cart save in session, not database?
更新:我找到了解决问题的方法。 谢谢你的支持!
我正在用 ajax by ruby 在轨道上做简单的购物车。
更改购物车的数量项目时,我想 ajax 我的购物车页面。 我找到了一些解决方案,但他们将购物车保存到数据库中。 如何在不将购物车保存到数据库的情况下解决我的解决方案?
我想知道:
我对我的问题也有一些想法。 但这太难了。 Exp:我想我会创建一个 _quantity_item 显示输入数量。 我可以将它用于购物车的索引视图并以增量/减量.js.erb 呈现但失败。 好难过!
我的视图展示车(短):
<% @cart.each_with_index do |item, index| %>
<tr>
<th scope="row"><%= index %></th>
<td><img src="<%= asset_path(item[0].image) %>" style="width:100px"></td>
<td><%= item[0].name %></td>
<td><%= money_vn_format(item[0].price) %></td>
<td>
<div class="quantity">
<%= button_to '-', decrement_item_path(item[0].id), class: 'btn minus1', method: :put, remote: true %>
<input class="quantity" min="0" value="<%= item[1] %>" type="number">
<%= button_to '+', increment_item_path(item[0].id), class: 'btn add1', method: :put, remote: true %>
</div>
</td>
<td><%= money_vn_format(item[0].price * item[1]) %></td>
<td><%= link_to 'Remove', delete_cart_path(item[0].id) %></td>
</tr>
<% end %>
和代码 CartsController:
# frozen_string_literal: true
class CartsController < ApplicationController
def index
save_session_to_cart if session.key? :cart
end
def add
session[:cart] ||= {}
session[:cart][params[:id]] = 1 unless session[:cart].key? params[:id]
save_session_to_cart
redirect_to carts_index_path
end
def delete
session[:cart].delete params[:id]
redirect_to carts_index_path
end
def destroy
reset_session
redirect_to carts_index_path
end
def increment_item
session[:cart][params[:id]] += 1
save_session_to_cart
redirect_to carts_index_path
end
def decrement_item
session[:cart][params[:id]] -= 1 if session[:cart][params[:id]] > 1
save_session_to_cart
redirect_to carts_index_path
end
private
def save_session_to_cart
@cart = []
@total = 0
session[:cart].each do |product_id, quantity|
@cart << [Product.find(product_id), quantity]
@total += Product.find(product_id).price * quantity
end
@cart
end
end
通过crispychicken Rails 查看这个答案:如何在 session 中存储数据? . 海报建议在 rails 中使用session
变量。
或者相反,如果您希望它更简单,请使用 JS 使用浏览器的本地存储。
我会使用浏览器的本地存储和 javascript 来做到这一点。 您可以使用以下方法保存值:
localStorage.setItem('items-count', 1);
然后像这样读回来:
localStorage.getItem('items-count');
但请记住,如果用户打开不同的浏览器或使用其他设备,购物车将是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.