Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

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>

<tbody>
  <% @users.each do |user| %>
    <tr>
      <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>
    </tr>
  <% end %> 
</tbody>

</table>

<br>

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

</div>


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 }
#has_secure_password
validates :password, presence: true, length: { minimum: 2 }

end


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.