Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method each rails error

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://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.

like image 675
Micheal Avatar asked Jan 31 '13 14:01

Micheal


1 Answers

The problem comes from the @users variable that does not exists:

In your index action you set @user to all users:

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 @user to @users and it will be okay ;)

def index
  @users = User.all
end
like image 83
MrYoshiji Avatar answered Oct 20 '22 14:10

MrYoshiji