2017-09-13 34 views
0

我無法增加購物車中物品的數量。它只會添加一個,然後它切換到「刪除」按鈕。有什麼方法可以重新配置,以便我可以添加多個項目?使用rails和redis增加購物車中的物品

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() 

回答

0

其實我對我自己想通了這一點。這些物品現在被保存到一個數組中,現在可以將多個物品添加到購物車中。 「添加到」按鈕也不再在「添加到」和「從中刪除」之間來回切換。 '刪除'按鈕現在是分開的。

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 
相關問題