未定义的方法`user_path' [英] undefined method `user_path'

查看:49
本文介绍了未定义的方法`user_path'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试手动构建用户模型(不使用 routes.rb 文件中的 'resources :users').我的 routes.rb 文件如下所示:

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:

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

这是我的索引视图:

<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
  <% @users.each do |user| %>
    <li>
      <%= link_to user.email, user %>
    </li>
  <% end %>
</ul>
<%= will_paginate %>

当我点击 localhost:3000/all_users 时收到此错误消息:

I get this error message when I hit localhost:3000/all_users:

undefined method `user_path'

我不知道这是从哪里来的.

I don't see where this is coming from.

好的,我发现在视图中将 'user' 更改为 '@user' 就可以了:

Ok, I've discovered that changing 'user' to '@user' in the view makes it work:

<%= link_to user.email, @user %>

但我真的不明白错误信息,或者'user'和'@user'之间的真正区别.另外,点击创建的链接不会重定向到用户页面,它停留在 localhost:3000/all_users 上.

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.

推荐答案

match '/users/:id', :to => 'users#show' 

应该

match '/users/:id', :to => 'users#show', :as => :user

:as 参数告诉路由器将路由命名为什么(然后你可以将 _path_url 添加到任何 _url>:as 参数是).

The :as parameter tells the router what to name the route as (You can then add _path or _url to whatever the :as parameter is).

此外,任何时候您直接链接到 ActiveRecord 模型(例如 link_to user.email, user),它都会尝试将 user 转换为 user_path.

Also, any time you link directly to an ActiveRecord model (e.g. link_to user.email, user), it will try to turn user into user_path.

这篇关于未定义的方法`user_path'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆