Ruby-on-rails 未定义的方法`user_path'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5136940/
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
undefined method `user_path'
提问by Bazley
I am trying to construct a users model manually (without using 'resources :users' in the routes.rb file). My routes.rb file looks like this:
我正在尝试手动构建用户模型(不使用 routes.rb 文件中的“资源:用户”)。我的 routes.rb 文件如下所示:
match '/users/:id', :to => 'users#show'
match '/all_users', :to => 'users#index'
This is my index method in the users controller:
这是我在用户控制器中的索引方法:
def index
@title = "All users"
@users = User.paginate(:page => params[:page])
end
This is my index view:
这是我的索引视图:
<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
<% @users.each do |user| %>
<li>
<%= link_to user.email, user %>
</li>
<% end %>
</ul>
<%= will_paginate %>
I get this error message when I hit localhost:3000/all_users:
当我点击 localhost:3000/all_users 时,我收到此错误消息:
undefined method `user_path'
I don't see where this is coming from.
我不明白这是从哪里来的。
EDIT:
编辑:
Ok, I've discovered that changing 'user' to '@user' in the view makes it work:
好的,我发现在视图中将 'user' 更改为 '@user' 可以使它工作:
<%= link_to user.email, @user %>
But I really don't understand the error message, or the real difference between 'user' and '@user'. Plus, clicking on the link created does not redirect to the user's page, it stays on localhost:3000/all_users.
但我真的不明白错误信息,或者“用户”和“@user”之间的真正区别。另外,点击创建的链接不会重定向到用户页面,它停留在 localhost:3000/all_users 上。
回答by Dylan Markow
match '/users/:id', :to => 'users#show'
should be
应该
match '/users/:id', :to => 'users#show', :as => :user
The :asparameter tells the router what to name the route as (You can then add _pathor _urlto whatever the :asparameter is).
该:as参数告诉路由器将路由命名为什么(然后您可以添加_path或添加_url到任何:as参数)。
Also, any time you link directly to an ActiveRecord model (e.g. link_to user.email, user), it will try to turn userinto user_path.
此外,任何时候您直接链接到 ActiveRecord 模型(例如link_to user.email, user),它都会尝试user变成user_path.
回答by BilalReffas
For everyone who using rails 4 in your routes.rb post '/users', :to => 'users#create', :as => :userand you controller render json: @user, status: :created, location: @user_path
对于在你的 routes.rbpost '/users', :to => 'users#create', :as => :user和你的控制器中使用 rails 4 的每个人render json: @user, status: :created, location: @user_path

