Im following the RoR tutorial by Michael Hartl and im at chapter 9.3 “Showing all users” so far everything has worked great but now I am getting an undefined method `each’ for nil:NilClass when trying to retrieve my users from the SQlite database. Here is my controller
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update]
before_filter :correct_user, only: [:edit, :update]
.
.
.
def index
@users = User.all
end
end
and my index.html.erb
<ul class="users">
<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>
<% end %>
</ul>
With this code i get the error undefined method `each’ for nil:NilClass
And when i change it to
<ul class="users">
<% if @users %>
<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>
<% end %>
<% end %>
</ul>
I can render the view but displaying 0 users although i have users in my db. I have created some manually and also used the ‘faker’ gem to spawn some. In the rails console typing User.all returns an array with 100 users. I cant seem to find the missing link here. Im also using the SQlite Database browser app to check out my User model where i also have 100 Users.
I have worked a lot with this and cant seem to figure things out.
Here is my User.rb aswell
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
It’s curious that
User.allis returningnilinstead of an empty array[]. Try the following:make sure you’ve run any pending migrations
If the previous step didn’t run any migrations, try wiping your database and starting again, just for good measure:
go into a rails console, and make sure
User.allis behaving correctlyIf this all works, try putting some debug statements into your controller (using pry or the ruby debugger is optimal, but even some
putsstatements will suffice here) to examine the value of@usersNext, you’ll want to either add some seeds to the database (edit db/seeds.rb and run
rake db:seed) or use scaffolded forms to add some users.