簡體   English   中英

如何更新購物車中的產品數量並在滑軌上的紅寶石上的購物車頁面中顯示總金額?

[英]How to update quantity of product in the cart and display total amount in cart page on ruby on rails?

現在,我正在做購物車項目,遇到了一些我不知道如何將價值從視圖傳遞到紅寶石的模型的問題。 所有編碼都在這里=> https://github.com/Gtar69/artstore_hw2

我的想法是我想在view / carts / index.html中輸入數量,並將數量vars傳遞給model / carts.rb進行一些簡單的計算,以將total_price呈現在購物車中...但是我不知道如何要做到這一點!

很感謝 !!!

在view / carts / index.html中

<tbody>


 <% current_cart.items.each do |product| %>
    <tr>
          <td><%= render_product_photo(product.default_photo) %></td>


        <td> 
          <%= link_to(product.title, admin_product_path(product)) %>
        </td>
        <td> <%= product.price %> </td>
        <td><input type="number" name= product.id  value="1"/></td> 
        <td><%= link_to("刪除物品",  delete_item_carts_path(:product_id => product.id) , :method => :post , :class => "btn btn-primary btn-lg btn-danger") %></td>
      </tr>
      <% end %>

    </tbody>
  </table>

  <div class="total group">
    <span class="pull-right">
       <span> 總計 <%= render_cart_total_price(current_cart) %> NTD  
    </span>
  </div>


  <div class = "checkout">
      <%= link_to("刪除全部", delete_all_carts_path,:method => :post, :class => "btn btn-primary btn-lg btn-danger pull-left") %>
  </div>

  <div class="checkout">
      <%= link_to("確認結賬", "#" , :method => :post , :class => "btn btn-primary btn-lg btn-danger pull-right") %>
  </div>

在carts.rb中

class Cart < ActiveRecord::Base

  has_many :cart_items, :dependent => :destroy
  has_many :items, :through => :cart_items, :source => :product


  def add_product_to_cart(product)
    items << product
    # cart_items和product
  end

  def remove_product_from_cart(product)
    items.destroy(product)
    #cart_items.where(:product_id => product.id).destroy_all 
  end  

  def remove_all_products_in_cart
    items.destroy_all 
    #clear => destory_all
  end  

  def total_price
    items.inject(0){|sum, item| sum +item.price}
  end  

end

在carts_helper中

module CartsHelper
  def cart_items_count(cart)
    cart.cart_items.count
  end  

  def render_cart_total_price(current_cart)
    current_cart.total_price
  end


end

首先,我不建議在助手中使用該功能。

其次,您認為:

<div class="total group">
    <span class="pull-right">
       <span> 總計 <%= current_cart.total_price %> NTD  
    </span>

您的模型:

def total_price
   self.items.pluck(:price).inject(:+)
end

Pluck將從price列返回一個數組,並且注入將添加數組中的所有元素。

希望有效!

暫無
暫無

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

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