Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


undefined method `each' for nil:NilClass


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)


View stream Index

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

<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>
          <% end %>
        <%= link_to post, method: :delete, data: { confirm: 'Are you sure?' } do %>
        <span class="glyphicon glyphicon-trash"></span>
          <% end %>
       <% end %>

  <% end %>


1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,440 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.