2014-07-21 40 views
1

對不起,如果這真的很明顯,我有點新,但無法在任何地方找到答案。Ruby on Rails:將特定的每個值傳遞到方法

我想創建一個按鈕,在我的索引視圖中增加一個項目的數量。

我有一個簡單的表項與列:|名稱|品牌|類型|數量|

我的控制器:

def index 
    @items = Item.all 
end 
def incr_quantity 
    Item.find(params[:id]).increment!(:quantity, by = 1) 
end 

在我看來,我有3所選擇的每個項目旁邊:

<% @items.each do |item| %> 
     <tr> 
     <td><%= image_tag(item.profile_url(:thumb)) %></td> 
     <td><%= item.name %></td> 
     <td><%= item.brand %></td> 
     <td><%= item.type %></td> 
     <td><%= item.quantity %></td> 
     <td><%= link_to 'Edit', edit_item_path(item) %></td> 
     <td><%= link_to 'Delete', item_path(item), method: :delete, data: {confirm: 'Are you sure?'} %></td> 
     <td><%= link_to 'Use 1 Item',item_incr_quantity_path(item), method: :post %></td> 

     </tr> 
    <% end %> 
</table> 

正如你可能已經猜到了,我得到的錯誤「無法找到沒有ID的物品「,只要我點擊超級鏈接」使用1物品「,但我無法弄清楚如何通過它們點擊的索引表中物品的特定物品ID。

正如指出:我應該包括我的路線文件來幫助回答這個好一點:

resources :items do 
    post "incr_quantity" 
end 

和要求是這樣的:

Parameters: 

{"_method"=>"post", 
"authenticity_token"=>"XXXXXXXXXX", 
"item_id"=>"3"} 
+0

我們可以看到你試圖增加數量的控制器嗎? – JTG

+0

您可以在routes.rb中顯示您定義incr_quantity路徑的部分嗎?該項目ID可能被傳遞爲'params [:item_id]'而不是'params [:id]' – akhanubis

回答

3

看着你的方式已經定義了指向item_incr_quantity_path (item)的鏈接,我相信你已經定義了incr_quantity這樣的路線:

resources :items do 
    post "incr_quantity" 
end 

這將創建如下incr_quantity行動路線:

item_incr_quantity POST /items/:item_id/incr_quantity(.:format) items#incr_quantity 

,您可以通過運行rake routes命令來驗證。

在這種情況下,您應該使用params[:item_id]而不是params[:id]

def incr_quantity 
    Item.find(params[:item_id]).increment!(:quantity, by = 1) 
end 
+0

你是完全正確的,它現在可以工作。謝謝! – MKunz

+0

很高興幫助。 :) –

相關問題