Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Irina Kalashnikova
Irina Kalashnikova
839 Points

NoMethodError in Users#index undefined method `each' for nil:NilClass

Hello I have this error and I have no idea how to fix it. Any help?

ruby *********index.html.rb*********************

<div class="container"> <p id="notice"><%= notice %></p>

<h1>Listing Users</h1>

<table> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Email</th> <th>Date of birth</th> <th>Gender</th> <th>Password_hash</th> <th colspan="3"></th> </tr> </thead>

  <% @users.each do |user| %>
      <td><%= user.first_name %></td>
      <td><%= user.last_name %></td>
      <td><%= user.email %></td>
      <td><%= user.date_of_birth %></td>
      <td><%= user.gender %></td>
      <td><%= user.password_hash %></td>
      <td><%= link_to 'Show', user %></td>
      <td><%= link_to 'Edit', edit_user_path(user) %></td>
      <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  <% end %> 



<%= link_to 'New User', new_user_path %>


class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

before_save { self.email = email.downcase }
validates :first_name, presence: true, length: { maximum: 25 }
validates :last_name, presence: true, length: { maximum: 50 }
validates :gender, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
          format: { with: VALID_EMAIL_REGEX },
          uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 2 }


1 Answer

Your @users variable is empty and your app was not able to retrieve user records from the database. Check to see if your database contains records in the users table. Also, make sure @users is being set in the controller.