Ruby-on-rails 未定义的方法每个 rails 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14628692/
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-09-02 21:21:24  来源:igfitidea点击:

undefined method each rails error

ruby-on-railsrubyruby-on-rails-3.1ruby-on-rails-3.2

提问by Micheal

I was trying out ruby on rails through the tutorial located at http://ruby.railstutorial.org. I got to to the point where I could create users and have their name and gravatar displayed at:

我正在通过http://ruby.railstutorial.org上的教程尝试使用 ruby​​ on rails 。我已经到了可以创建用户并在以下位置显示他们的姓名和头像的地步:

http://localhost:3000/users/1

Now I want to display all users when a user goes to:

现在我想在用户访问时显示所有用户:

http://localhost:3000/users/

Here is my controller:

这是我的控制器:

class UsersController < ApplicationController

  def index
    @user = User.all
  end      

  #...
end

Here is my view.

这是我的看法。

#View for index action in user's controleer

<h1>All users</h1>

<ul class="users">
  <% @users.each do |user| %>
    <li><%= user.content %></li>
  <% end %>
</ul>

I get the following error.

我收到以下错误。

undefined method `each' for nil:NilClass

Can someone tell me why the index page is not working as I want it to.

有人能告诉我为什么索引页没有按我想要的那样工作。

回答by MrYoshiji

The problem comes from the @usersvariable that does not exists:

问题来自@users不存在的变量:

In your index action you set @userto all users:

在您@user为所有用户设置的索引操作中:

def index
  @user = User.all
end

By convention, we use pluralized names when we retrieve several entries from the DB, that's why you are calling @users(notice the 's') in the view. Just rename your @userto @usersand it will be okay ;)

按照惯例,当我们从数据库中检索多个条目时,我们使用复数名称,这就是您@users在视图中调用(注意“s”)的原因。只需将您的名称重命名@user@users,就可以了 ;)

def index
  @users = User.all
end