【问题标题】:adding more than one item to a cart using redis and rails使用 redis 和 rails 将多个项目添加到购物车
【发布时间】:2015-02-01 05:16:51
【问题描述】:

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

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

与电影相反,我有面板。模型、视图和控制器如下所示

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,任何帮助将不胜感激!

【问题讨论】:

    标签: javascript ruby-on-rails coffeescript redis


    【解决方案1】:

    我发现实现此目的的一种方法是将面板 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 },然后您可以参考。(需要注意的是,数量将作为字符串返回)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2020-01-14
      • 1970-01-01
      • 2017-07-23
      • 2022-11-10
      相关资源
      最近更新 更多