undefined method `each' for nil:NilClass... why?

In your posts controller, you need to define @posts, which, based on the error you haven't.

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end 

As @posts is not defined calling each on it will generate undefined methodeach' for nil:NilClass`.


To explain more about this error whenerver you encounter

  undefined method `each' for nil:NilClass

The error clearly complaints that you're calling each method on something here(@posts) which is nil. That means you've not defined it in your controller. Since you didn't define it, that's why it is complaining undefined method for nil class.

Please makes sure to check whenever you call an instance variable from your view? you must have to define that in your controller to be accessible in views.

Sometimes you'll also get this error if you call a private method in your controller.