JamesRocky
JamesRocky

Reputation: 721

Rails: How do I show all the users post? undefined method `user' for nil:NilClass

I was testing out a blog. If a user posts in the blog, when they go to the index, it shows all the users name. But if the user logs out and go to the index page, they get an error.

undefined method `user' for nil:NilClass

It seems to not show the other users post unless he or she is logged in or this error comes. Why is that happening? Any help would be appreciated.

index.html

<% @posts.each do |post| %> 

      <%= image_tag(post.user.avatar.url(:thumb)) %>
      <%= link_to post.user.name, @post.user %> 
 <% end %>

Upvotes: 0

Views: 74

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Try this

<% @posts.each do |post| %> 
  <% unless post.user.blank? %>
    <%= image_tag(post.user.avatar.url(:thumb)) %>
    <%= link_to post.user.name, post.user %> 
  <% end %>
<% end %>

Hope this helped!

Upvotes: 1

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Change

<%= link_to post.user.name, @post.user %> 

to

<%= link_to post.user.name, post.user %> 

Upvotes: 4

Related Questions