Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No route matches missing required keys: [:id]

I'm new at Rails and I've seem similar problems, but I can't solve mine.

My routes:

resources :users do
    resources :items
end

My models:

class Item < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
   has_many :items
end

HTML:

<% @items.each do |item| %>
<tr>
  <td><%= item.id %></td>
  <td><%= item.code %></td>
  <td><%= item.name %></td>
  <td><%= item.quantity %></td>
  <td><%= link_to "Edit", edit_user_item_path(item) %></td>  <---- error

And I'm getting the same error:

No route matches {:action=>"edit", :controller=>"items", 
:user_id=>#<Item id: 1, user_id: 1, code: "123", name: "test", 
quantity: 12, , created_at: "2014-02-11 15:45:30", updated_at:
"2014-02-11 15:45:30">, :id=>nil, :format=>nil} missing required keys: [:id]
like image 264
letz Avatar asked Feb 11 '14 17:02

letz


4 Answers

You need to include the user as well since its a nested route. So something like:

<td><%= link_to "Edit", edit_user_item_path(@user, item) %></td>
like image 144
jklina Avatar answered Oct 09 '22 09:10

jklina


The problem is that you are using nested resources:

resources :users do
   resources :items
end

So when you have a link:

<%= link_to "Edit", edit_user_item_path(item) %> 

It will lack one user_id so the easy to check the issue is using rake routes. And it will list the routes like this:

edit_user_item GET    /users/:user_id/items/:id/edit(.:format) items#edit

You can see the routes above and check it with the link, you will see it does not have user_id. That's the main reason!

like image 40
Hai Nguyen Avatar answered Oct 09 '22 07:10

Hai Nguyen


You've missed user_id in the following path:

edit_user_item_path(user_id, item)

format you are able to find just running bundle exec rake routes | grep edit_user_item

like image 27
itsnikolay Avatar answered Oct 09 '22 09:10

itsnikolay


The object item is being passed instead of the required id.

<td><%= link_to "Edit", edit_user_item_path(item.id) %></td>
like image 31
Zero Fiber Avatar answered Oct 09 '22 09:10

Zero Fiber