![](/img/trans.png)
[英]adding more than one list item into List at a time when the items are generated dynamically (using NAPA)
[英]adding more than one item to a cart using redis and rails
我一直在遵循本指南,了解如何使用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,因此不勝感激!
我發現完成此操作的一種方法是將面板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},您可以隨后引用該哈希。(應注意,數量將作為字符串返回)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.