[英]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.