我刚刚学习了使用 Rails 3rd Ed. 进行的敏捷 Web 开发,我正在阅读 Depot 应用程序章节,我正在尝试创建一个简单的编辑数量函数和删除函数。我对删除功能很幸运,但对编辑数量功能没有运气。
我将提供很多信息,所以请不要感到不知所措。我发现这是一个具有挑战性的问题。
到 add_to_cart.html.erb
<div class="cart-title">Your cart</div>
<table>
<% for item in @cart.items %>
<tr>
<td><% form_for @cart.items, :url => {:action => "cart_update", :id => "#{item.getinventoryid}"} do |f| %>
<%= f.text_field :quantity, :size => '3' %>
<%= f.hidden_field :id, :value => "#{item.getinventoryid}" %>
<%= f.submit 'cart_update' %>
<% end %></td>
<td><%=h item.quantity %> ×</td>
<td><%=h item.title %></li></td>
<td><%=h item.description %></td>
<td class="item-price"><%= number_to_currency(item.price) %></td>
<td><%= link_to 'remove', {:controller => 'inventories', :action => 'remove_cart_item', :id => "#{item.getinventoryid}"} %></td>
</tr>
<% end %>
<tr class="total-line">
<td colspan="4">Total</td>
<td class="total-cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Checkout", :action => 'checkout' %>
<%= button_to 'Empty cart', :action => 'empty_cart' %>
库存控制器:
def cart_update
@inventory = Inventory.find(params[:id])
@cart = find_cart
@cart.increment_inventory_quantity(params[:inventory])
end
def remove_cart_item
inventory = Inventory.find(params[:id])
@cart = find_cart
@cart.remove_inventory(inventory)
redirect_to_index("The item was removed")
end
Cart.rb 模型
attr_accessor :items
def increment_inventory_quantity(id, quantity)
inventory_to_increment = @items.select{|item| item.inventory == inventory}
# We do this because select will return an array
unless product_to_increment.empty?
inventory_to_increment = inventory_to_increment.first
else
# error handling here
end
inventory_to_increment.quantity = quantity
end
def remove_inventory(inventory)
@items.delete_if {|item| item.inventory == inventory }
end
cart_item.rb 模型
attr_accessor :inventory, :quantity
def getinventoryid
@inventory.id
end
这会产生奇怪的结果:
请注意,数量16出现在我的循环 (#Fail) 的两个项目中。当我提交表单时,InventoriesController# cart_update中的 ArgumentError 参数数量错误(1 对 2)返回错误。传递的参数:
{"commit"=>"cart_update",
"_method"=>"put",
"authenticity_token"=>"sH1tWXTJPltpSq5XaAkww7259IR5ZiflnqSFB2Zb0IY=",
"id"=>"50",
"cart_item"=>{"quantity"=>"16",
"id"=>"50"}}