【发布时间】:2020-08-30 18:31:13
【问题描述】:
更新:我找到了解决问题的方法。感谢您的支持!
我正在通过 ruby on rails 使用 ajax 做简单的购物车。
我想在更改购物车的数量项目时 ajax 我的购物车页面。我找到了一些解决方案,但他们将购物车保存到数据库中。如何在不将购物车保存到数据库的情况下解决我的解决方案?
我想知道:
- 我可以在文件视图中使用 ajax 或在视图中包含 ajax 文件吗?就像我在 PHP 中尝试过的那样?
- 如果我在 Rails 上使用 ajax 默认值,如何在文件 increment/decrement_item.js.erb 中呈现输入字段(更改值)(文件呈现部分而不重新加载页面)?我不使用购物车作为活动记录,所以渲染@cart 或@item 是不可能的(或者我不知道如何使它成为可能)。
我对我的问题也有一些想法。但这太难了。 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
【问题讨论】:
标签: ruby-on-rails ajax