如何更新购物车中的产品数量并在轨道上的红宝石上显示购物车页面中的总金额?

时间:2014-06-17 15:33:44

标签: ruby-on-rails ruby-on-rails-3

现在,我正在做购物车项目并遇到了一些我不知道的问题 如何在轨道上的ruby中将值从视图传递到模型。 所有编码都在这里=> https://github.com/Gtar69/artstore_hw2

我的想法是我想在view / carts / index.html中输入数量 并将数量变量传递给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>

in 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

in 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

1 个答案:

答案 0 :(得分:0)

首先,我不建议在帮助程序中使用该函数。

其次,在您看来:

<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列返回一个数组,并且inject将添加数组中的所有元素。

希望有效!