How do I pass 2 arguments using a simple form?
I have a very simple cart which displays the item quantity in a text_field, and the item name. I can fetch the proper data, I can't pass both of my arguments into my method (inventory ID and quantity). I'm receiving an argument error in my cart_update method of the inventories controller.
add_to_cart.html.erb
<% for item in @cart.items %>
<tr>
<td><% form_for item, :url => {:action => "cart_update", :id => "#{item.getinventoryid}", :quantity => "3"} do |f| %>
<%= f.text_field :quantity, :size => '3' %>
<%= f.hidden_field :id, :value => "#{item.getinventoryid}" %>
<%= f.submit 'cart_update' %>
<% end %></td>
<td><%=h item.title %></li></td>
</tr>
<% end %>
cart_item.rb model
attr_accessor :inventory, :quantity
def initialize( inventory )
@inventory = inventory
@quantity = 1
end
cart.rb model
attr_accessor :items
def increment_inventory_quantity(inventory, quantity)
inventory_to_increment = @items.select{|item| item.inventory == inventory}
# We do this because select will return an array
unless inventory_to_increment.empty?
inventory_t开发者_Python百科o_increment = inventory_to_increment.first
else
# error handling here
end
inventory_to_increment.quantity = quantity
end
inventories_controller.rb
def cart_update
@inventory = Inventory.find(params[:id])
@cart = find_cart
@cart.increment_inventory_quantity(params[:inventory])
end
The error reads: ArgumentError in InventoriesController#cart_update
inventories_controller.rb:24:in increment_inventory_quantity'
inventories_controller.rb:24:in
cart_update'
With the following Parameters:
{"commit"=>"cart_update",
"quantity"=>"3",
"_method"=>"put",
"authenticity_token"=>"CK6to1uGWPszjz8vfL1Er3DLgi8cIMtLxfFb49a4wCE=",
"id"=>"5",
"cart_item"=>{"quantity"=>"11",
"id"=>"5"}}
I'm really confused because it appears I'm passing the parameters I need. Additionally the url is formatted as: http://localhost:3000/inventories/cart_update/5?quantity=3
which is also what I was expecting to see. What am I doing that is obviously wrong?
Thanks in Advance!
Just change line 3 of cart_update
, and use this instead:
if(params[:cart_item] && params[:cart_item][:id])
@cart.increment_inventory_quantity(params[:cart_item][:id], params[:cart_item][:quantity])
else
# Error handling
end
You can see from your POST data:
{ ... ,
"cart_item"=>{"quantity"=>"11", "id"=>"5"}
}
That rails is nesting the cart_item
details into its own hash.
精彩评论