gpt4 book ai didi

javascript - 使用 redis 和 rails 将多个项目添加到购物车

转载 作者:可可西里 更新时间:2023-11-01 11:21:43 26 4
gpt4 key购买 nike

我一直在关注本指南,了解如何使用 Rails、Redis 和 Braintree API 创建购物车。 http://www.sitepoint.com/build-online-store-rails/

该指南介绍了如何将单部电影添加到购物车,一旦您将该电影添加到购物车,唯一可用的选项就是将其从购物车中删除。我正在尝试这样做,以便我可以在购物车中添加同一部电影的多个副本。我如何实现这个目标?

与电影相反,我有面板。下面给出模型、 View 和 Controller

panels.rb

class Panel < ActiveRecord::Base
has_many :purchases
has_many :buyers, through: :purchases

def cart_action(current_user_id)
if $redis.sismember "cart#{current_user_id}", id
"Remove from"
else
"Add to"
end
end
end

panels_controller.rb

class PanelsController < ApplicationController
before_action :logged_in_user
before_action :set_panel, only: [:show, :edit, :update, :destroy]

# GET /panels
# GET /panels.json
def index
@panels = Panel.all
end

def show
@panel = Panel.find(params[:id])
@cart_action = @panel.cart_action current_user.try :id
end



panels/show.html.erb

<p id="notice"><%= notice %></p>

<p>
<strong>Title:</strong>
<%= @panel.title %>
</p>

<p>
<strong>Location:</strong>
<%= @panel.location %>
</p>

<p>
<strong>Price:</strong>
<%= @panel.price %>
</p>

<%=link_to "", class: "btn btn-danger", data: {target: @cart_action, addUrl: add_to_cart_path(@panel), removeUrl: remove_from_cart_path(@panel)} do%>
<i class="fa fa-shopping-cart"></i>
<span><%=@cart_action%></span> Cart
<%end%>

panels.js.coffee
$(window).load ->
$('a[data-target]').click (e) ->
e.preventDefault()
$this = $(this)
if $this.data('target') == 'Add to'
url = $this.data('addurl')
new_target = "Remove from"
else
url = $this.data('removeurl')
new_target = "Add to"
$.ajax url: url, type: 'put', success: (data) ->
$('.cart-count').html(data)
$this.find('span').html(new_target)
$this.data('target', new_target)

由于我是从本指南开始才开始接触 Redis 的,任何帮助将不胜感激!

最佳答案

我发现实现此目的的一种方法是将面板 ID 添加到哈希中,其中键是面板 ID,数量是值:

{ panel_id => qty }

使用 hmset :

$redis.hmset current_user_cart, panel, item_qty

这将在 current_user_cart 键下添加 key=>value 对,以检索面板 ID,您可以使用 hkeys ,这将检索所有哈希键:

panel_ids = $redis.hkeys current_user_cart

然后调用 hgetall 获取数量:

@cart_qtys = $redis.hgetall current_user_cart

这将返回完整的散列,例如{ panel_id => qty },然后你可以引用它。(应该注意的是,数量将作为字符串返回)

关于javascript - 使用 redis 和 rails 将多个项目添加到购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com