Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

undefined method `each' for nil:NilClass

Hi,

I'm getting a NoMethodError in Stream#index for an undefined method `each' for nil:NilClass. Specifically for line:

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

Any help is greatly appreciated. Thank you in advance

Stream Controller

class StreamController < ApplicationController
 before_action :set_post, only: [:show, :edit, :update, :destroy]
 before_action :correct_user, only: [:edit, :update, :destroy]
 before_action :authenticate_user!, except: [:index, :show]

 def index
  Post.where(follower_id: current_user.id, followed_id: current_user.id)
 end

end

View stream Index

div class="page-header">
   <center><strong><h1> Stream Page </h1></strong></center>
</div>


<div id="posts" class="transitions-enabled">
   <% @posts.each do |post| %>

    <div class="box panel panel-default">
      <%= link_to image_tag(post.image.url(:medium)), post %>
      <div class="panel-body">
      <%= post.description %><br/>
      <strong><%= post.user.name if post.user %></strong>

      <% if post.user == current_user %>
        <div class="actions">
        <%= link_to edit_post_path(post) do %>
        <span class="glyphicon glyphicon-edit"></span>
            Edit
          <% end %>
        <%= link_to post, method: :delete, data: { confirm: 'Are you sure?' } do %>
        <span class="glyphicon glyphicon-trash"></span>
            Delete
          <% end %>
       </div>
       <% end %>
     </div>
    </div> 

  <% end %>
  </div>

   </section>
 </aside>
 </div>

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

In your stream controller, you are missing an instance variable. The line should look like this inside your index method:

@posts = Post.where(follower_id: current_user.id, followed_id: current_user.id)

Thanks Maciej. I missed that, smh. :) Now I'm getting a new error 'ActiveRecord::StatementInvalid'. I'm trying to sort through that. Thanks again. I need to pay more attention.