Rails 3rd Ed。を使用したアジャイルWeb開発を取り上げたところ、デポアプリケーションの章を読み、簡単な数量編集関数と削除関数を作成しようとしています。削除機能は運が良かったのですが、数量編集機能は運が悪かったです。
たくさんの情報を提供しますので、圧倒されないようにしてください。これは難しい問題だと思いました。
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' %>
inventories_controller:
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"}}