I am new to Rails and Ruby and actually it’s my first web language. This isn’t my first project but it’s the bigest so far and I am having trouble with a certain page (the “home” page).
The error is:
NoMethodError in Home#index undefined method `avatar' for nil:NilClass
Extracted source (around line #1):
1: <%= image_tag current_user.avatar.url(:thumb) %>
2: <ul>
3: <li><b>Name:</b><%= current_user.name %></li>
4: <li><b>Username:</b><%= current_user.username %></li>
So it doesn’t like my attributes 🙁 What should I do in this situation? Where should I look first? Is this a controller problem?
The problem is that
current_useris returningnil.Take a look at the error
Ruby is saying that you are trying to execute an instance method
avataron thenilobject. After looking at your code, you should be able to tell that you are callingavataron the return value ofcurrent_userso you can deduce thatcurrent_useris returningnilinstead of the user.Per the comments:
To solve this you will need to first determine if there is a
current_user. Then and only then do you try to display a usersavataror the users other attributes (name,username…)Some people do not like logic in the views, I tend to follow this practice.
To avoid this, you could: create a view helper that contains the logic. This helper may or may not display/return data about a user.
Something along the lines of
if current_user ...