簡體   English   中英

Rails購物車不會在第二次添加時更新

[英]Rails cart won't update on second addition

我有一個購物車,可以添加一個項目,並且將顯示一個購物車,顯示數量為1的購物車中的項目,當我向購物車中添加相同的項目時,它會被添加,但是直到我添加再次或同一項目,或刷新購物車。 添加相同的第三個項目將更新購物車並顯示正確的數量,添加第二個相同的項目后它不會更新,並且將顯示較少的數量,直到刷新頁面或添加其他內容為止。購物車!

該代碼主要來自《敏捷的帶Rails的Web開發》 3.2版。

line_items/create.js.erb
if ($('#cart tr').length > 0) { $('#cart').show(); }
$('#cart').html("<%=j render @cart %>");



class LineItemsController < ApplicationController
      def create
        @cart = current_cart
        item = Item.find(params[:item_id])
          @line_item = @cart.add_item(item.id)
          respond_to do |format|
            if @line_item.save
              puts @cart
              format.js { @current_item = @line_item}
              format.html { redirect_to store_url,
                notice: "#{item.name} added to cart." }
              format.json { render json: @line_item,
                status: :created, location: @line_item }
            else
              format.html { render action: "new" }
              format.json { render json: @line_item.errors,
                status: :unprocessable_entity }
            end
          end
      end

    end

carts/show.html.haml
= render @cart

carts/_cart.html.haml
= render cart.line_items



line_items/_line_item.html.erb

   <% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td><%= line_item.quantity %> &times;</td>
<td><%= line_item.item.name %></td>
<td class="item_price"><%= number_to_pounds(line_item.total_price) %></td>
</tr>




class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy
  # attr_accessible :title, :body

  def add_item(product_id)
    current_item = line_items.find_by_item_id(product_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(item_id: product_id)
    end
    current_item
  end

@cart對象總是落后一步,因為保存后不會更新。 保存在line_items控制器中后,設置@cart = current_cart是可行的,就像渲染購物車視圖時使用@cart.reload

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM