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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With