Ruby-on-rails – undefined method `each’ for nil:NilClass… why

ruby-on-railsundefined

rails guide example, click the button save post, console show this message:

Started POST "/posts" for 127001 at 2013-12-25 22:42:04 +0800
Processing by PostsController#create as HTML Parameters:
{"utf8"=>"✓", "authenticity_token"=>"CLalUww3gqnSlED0AWdou6P/U2qya
vPqDiBANQOuYgA=", "post"=>{"title"=>"11", "text"=>"22"},
"commit"=>"Save Post"} (0.0ms) begin transaction (0.0ms)
rollback transaction Redirected to http:// 127001:3000/posts
Completed 302 Found in 16ms (ActiveRecord: 0.0ms)

Started GET "/posts" for 127001 at 2013-12-25 22:42:04 +0800
Processing by PostsController#index as HTML Rendered
posts/index.html.erb within layouts/application (15.6ms) Completed 500
Internal Server Error in 31ms

ActionView::Template::Error (undefined method `each' for
nil:NilClass):

        <th>Text</th>
        </tr>
        <% @posts.each do |post| %>

======================================================

routes is correct, why post is nil? rails 4.0.2 ruby 2.0

Best Answer

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`.