简体   繁体   English

Ruby on Rails:将特定的.each值传递给方法

[英]Ruby on Rails: Passing specific .each value into method

Sorry if this is really obvious, I'm slightly new but could not find this answer anywhere. 对不起,如果这是非常明显的,我有点新,但无法在任何地方找到这个答案。

I am trying to create a button that increases the quantity of an item by one in my index view. 我正在尝试创建一个按钮,在我的索引视图中将项目数量增加一个。

I have a simple table items with the columns: |name|brand|type|Quantity| 我有一个简单的表项目列:|名称|品牌|类型|数量|

My Controller: 我的控制器:

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

In my view I have each item with 3 options next to it: 在我看来,我有每个项目旁边有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>

As you may have guessed I am getting the error "Couldn't find Item without an ID" whenever I click the hyperlink "Use 1 Item", but I cannot figure out how to pass the specific item ID for the item in the index table that they click on. 你可能已经猜到我每次点击超链接“使用1项”时都会收到错误“无法找到没有ID的项目”,但我无法弄清楚如何在索引表中传递项目的特定项目ID他们点击了。

As was pointed out: I should have included my routes file to help answer this a bit better: 正如所指出的:我应该包含我的路线文件以帮助解决这个问题:

resources :items do
  post "incr_quantity"
end 

and the Request looked like this: 请求看起来像这样:

    Parameters:

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

Looking at the way you have defined the link to direct to item_incr_quantity_path (item) , I am sure that you have defined the routes for incr_quantity something like: 看看你定义了指向item_incr_quantity_path (item)的链接的方式,我确信你已经定义了incr_quantity的路由,例如:

resources :items do
  post "incr_quantity"
end 

That would create a route for incr_quantity action as below: 这将为incr_quantity操作创建一个路由,如下所示:

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

which you can verify by running rake routes command. 您可以通过运行rake routes命令来验证。

In that case, you should be using params[:item_id] instead of params[:id] . 在这种情况下,您应该使用params[:item_id]而不是params[:id]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM