2010-01-18 33 views
0

我有一個非常簡單的購物車,它顯示項目數量在一個text_field和項目名稱。我可以獲取適當的數據,但無法將我的兩個參數都傳遞給我的方法(庫存ID和數量)。我在庫存控制器的cart_update方法中收到參數錯誤。如何使用簡單形式傳遞2個參數?

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模型

attr_accessor :inventory, :quantity 

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

cart.rb模型

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_to_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 

錯誤讀取:ArgumentError in InventoriesController#cart_update

inventories_controller.rb:24:在increment_inventory_quantity' inventories_controller.rb:24:in cart_update」

使用以下參數:

{"commit"=>"cart_update", 
"quantity"=>"3", 
"_method"=>"put", 
"authenticity_token"=>"CK6to1uGWPszjz8vfL1Er3DLgi8cIMtLxfFb49a4wCE=", 
"id"=>"5", 
"cart_item"=>{"quantity"=>"11", 
"id"=>"5"}} 

我真的很困惑,因爲它出現我傳遞我需要的參數。此外,網址格式爲:http://localhost:3000/inventories/cart_update/5?quantity=3這也是我期待看到的。我在做什麼顯然是錯誤的?

在此先感謝!

回答

0

只是改變線3 cart_update,並用這個代替:

if(params[:cart_item] && params[:cart_item][:id]) 
    @cart.increment_inventory_quantity(params[:cart_item][:id], params[:cart_item][:quantity]) 
else 
    # Error handling 
end 

您可以從POST數據看:

{ ... , 
    "cart_item"=>{"quantity"=>"11", "id"=>"5"} 
} 

這Rails是嵌套cart_item細節變成自己的哈希值。

+0

我跟着你的修復:返回是:未定義的方法爲[]'量=」:數組 與這些PARAMS: 參數: { 「提交」=> 「cart_update」, 「_method」=> 「放」, 「authenticity_token」=> 「CK6to1uGWPszjz8vfL1Er3DLgi8cIMtLxfFb49a4wCE =」, 「ID」=> 「5」, 「cart_item」=> { 「數量」=> 「1」, 「ID」=> 「5」 }} – 2010-01-18 05:43:44

+0

@JZ我認爲'#error handling here'意味着你在那裏有錯誤處理。你的'select'語句失敗,所以它返回一個空數組。你的腳本對數組不做任何處理,所以你最後一行'increment_inventory_quantity'正在有效地運行這個'[] .quantity = 1',這當然會失敗。 – 2010-01-18 06:17:09

+0

謝謝!我的#error處理標籤提示我以後再添加它。 – 2010-01-18 06:32:56