简体   繁体   中英

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:

  <% @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.

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:

resources :items do
  post "incr_quantity"
end 

That would create a route for incr_quantity action as below:

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

which you can verify by running rake routes command.

In that case, you should be using params[:item_id] instead of params[:id] .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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