[英]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.