简体   繁体   English

使用rails和redis增加购物车中的物品

[英]increase items in shopping cart using rails and redis

I am having trouble increasing the quantity of items in the cart. 我在增加购物车中的物品数量时遇到麻烦。 It will only add one, then the it switches to the 'remove' button. 它只会添加一个,然后切换到“删除”按钮。 Is there some way I can reconfigure this so I can add more than one of each item? 有什么方法可以重新配置它,以便我可以在每个项目中添加多个?

carts_controller.rb carts_controller.rb

def add
  $redis.sadd current_user_cart, params[:item_id]
  render json: current_user.cart_count, status: 200
end

carts.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)


  $('#mycart .remove').click (e) ->
    e.preventDefault()
    $this = $(this).closest('a')
    url = $this.data('targeturl')
    $.ajax url: url, type: 'put', success: (data) ->
      $('.cart-count').html(data)
      $this.closest('.cart-item').slideUp()

I actually figured this out on my own. 我实际上是自己解决这个问题的。 The items are now being saved to an array, now more than one can be added to the cart. 现在,这些商品已保存到一个阵列中,现在可以将多个商品添加到购物车中。 The 'add to' button is also no longer toggling back and forth between 'add to' and 'remove from'. “添加到”按钮也不再在“添加到”和“从中删除”之间来回切换。 The 'remove' button is now separate. 现在,“删除”按钮是单独的。

  def show
   cart_ids = $redis.lrange current_user_cart, -100, 100
   @cart_items = Item.find(cart_ids)
  end

 def add
  $redis.lpush current_user_cart, params[:item_id]
  render json: current_user.cart_count, status: 200
 end

 def remove
  $redis.lrem current_user_cart, 1, params[:item_id]
  render json: current_user.cart_count, status: 200
 end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM