Html 没有路由匹配缺少必需的键:[:id]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21708256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:54:11  来源:igfitidea点击:

No route matches missing required keys: [:id]

htmlruby-on-railsrubypathroutes

提问by letz

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

我是 Rails 的新手,我似乎遇到了类似的问题,但我无法解决我的问题。

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:

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]

回答by jklina

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>

回答by hainguyen

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_idso the easy to check the issue is using rake routes. And it will list the routes like this:

它将缺少一个,user_id因此易于检查问题的方法是使用rake routes. 它会列出这样的路线:

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!

您可以查看上面的路线并使用链接进行检查,您会看到它没有user_id. 这是主要原因!

回答by Zero Fiber

The object itemis being passed instead of the required id.

item正在传递对象而不是所需的 id。

<td><%= link_to "Edit", edit_user_item_path(item.id) %></td>

回答by itsnikolay

You've missed user_idin the following path:

您错过user_id了以下路径:

edit_user_item_path(user_id, item)

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

格式你可以找到只是运行 bundle exec rake routes | grep edit_user_item