16
votes

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

3
Please show the code of PostsController#index.Koraktor
thanks i know the reason, i used post ,should be posts.but now new issue raise undefined method `title' for nil:NilClassuser3134762

3 Answers

35
votes

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

12
votes

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.

2
votes

Try replacing this:

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

with

<% Post.all.each do |post| %>