I am trying to implement the following code in index.html.erb on rails and the following error appears on the server:
NoMethodError in Users#index
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Extracted source (around line #2)
<div id="users">
<% @users.each do |user| %>
<div id="user">
<% if user.username != current_user.username %>
<%=h user.username %>
<%= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post %>
<% end %>
</div>
<% end %>
</div>
Controller code:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
session[:user_id] = @user.id
redirect_to root_url, :notice => "Thank you for signing up! You are now logged in."
else
render :action => 'new'
end
end
end
def edit
@user = current_user
end
def update
@user = current_user
if @user.update_attributes(params[:user])
redirect_to root_url, :notice => "Your profile has been updated."
else
render :action => 'edit'
end
end
You’ll get this a lot with rails.
To explain:
The method does exist so the error message is confusing. The problem is that the variable (@users) doesn’t have any value. It’s nil rather than a valid object. So when you try to call that method on ‘nil’ you get that error message.
So look in your controller and make sure that the query e.g. @users = User.all does actually return records and you can also check that in the console (script/console or script/rails console)