2014-12-03 45 views
0

我一直在關注如何使用Rails,Redis和Braintree API創建購物車。 http://www.sitepoint.com/build-online-store-rails/使用redis和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><%[email protected]_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的,任何幫助將不勝感激!

回答

1

的一種方式,我發現做到這一點是對面板ID添加到一個哈希代替,其中關鍵是面板id和數量是值:

{ panel_id => qty } 

使用hmset

$redis.hmset current_user_cart, panel, item_qty 

這將增加鍵=>在current_user_cart項下值對,檢索麪板的id,你可以使用hkeys,這將檢索所有的哈希鍵:

panel_ids = $redis.hkeys current_user_cart 

然後拿到qtys你可以稱之爲hgetall:

@cart_qtys = $redis.hgetall current_user_cart 

將返回完整的哈希值,例如{panel_id => qty},然後你可以參考它(應該注意的是,數量將作爲字符串返回)

相關問題