繁体   English   中英

在Rails购物车中编辑ruby中的内容

[英]edit content in ruby on rails shopping cart

我正在尝试构建一个带导轨的简单购物车,现在可以将产品添加到购物车,我想知道如何在购物车中编辑产品,我正在使用会话来控制购物车中的产品。 这是用户添加到购物车时看到的内容:

<% @cart.items.each do |item| %>
<tr>
    <td>
        <%= image_tag item.pic , :alt => "#{item.title}" %>
    </td>
    <td>
        <%= link_to "#{item.title}" , store_path(item.product_id) %>
    </td>
    <td>
        <%= item.unit_price %>
    </td>
    <td>
        <%= item.quantity %>
    </td>
    <td>
        <%= item.total_price %>
    </td>
    <% end %>
</tr>

这是CartItem类:

class CartItem

  attr_reader :product, :quantity

  def initialize(product)
    @product = product
    @quantity = 1
  end

  def increment_quantity
    @quantity += 1
  end

  def product_id
    @product.id
  end

  def title
    @product.name
  end

  def pic
    @pic = @product.photo.url(:thumb)
  end

  def unit_price
    @product.price
  end

  def total_price
    @product.price * @quantity
  end

end

我想为用户提供编辑产品数量或移除产品的能力,而不仅仅是清除整个购物车。 我怎样才能做到这一点 ?

好吧,您已经进行了一些设置。 您的购物车项目模型中有increment_quantity方法,因此需要做的是设置购物车模型以允许您指定产品,然后调用新方法,如下所示:

cart.rb(假设这是您的购物车型号)

def increment_product_quantity(id, quantity)
   product_to_increment = @items.select{|product| product.product_id == id}

   # We do this because select will return an array
   unless product_to_increment.empty?
      product_to_increment = product_to_increment.first
   else
      # your error handling here
   end

   product_to_increment.quantity = quantity
end

def remove_product(id)
   @items.delete_if {|product| product.product_id == id }
end

现在,您将必须将购物车商品模型修改为数量不是attr_reader对象而是attr_accessor对象的情况,或者为购物车商品创建专门用于设置数量的方法; 你的选择。

还有其他一些事情可以做,但这大概是我现在推荐的最简单,最干净的方法。

好问题。 我能够使删除功能正常工作。 看来您在关注实用的程序员《 带有Rails的敏捷Web开发》第三版。

开始了...

要add_to_cart.html.erb

我在最后一个tr订单项旁边添加了以下表格行:

<td><%= link_to 'remove', {:controller => 'inventories', :action => 'remove_cart_item', :id => "#{item.getinventoryid}"} %></td>

到CartItem.rb模型

将attr_reader:inventory,:quantity更改为attr_accessor :inventory, :quantity

def getinventoryid
   @inventory.id
end

到Cart.rb模型:

将attr_reader:items更改为attr_accessor :items

def remove_inventory(inventory)
   @items.delete_if {|item| item.inventory == inventory }
end

要到ventory_controller.rb:

def remove_cart_item
  inventory = Inventory.find(params[:id])
  @cart = find_cart
  @cart.remove_inventory(inventory)
  redirect_to_index("The item was removed")
 end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM