Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 562
user3134762 Avatar asked Dec 25 '13 15:12

user3134762


3 Answers

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

like image 107
vee Avatar answered Oct 13 '22 01:10

vee


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.

like image 27
Prabhakar Undurthi Avatar answered Oct 13 '22 00:10

Prabhakar Undurthi


Try replacing this:

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

with

<% Post.all.each do |post| %>
like image 38
anosha_rehan Avatar answered Oct 13 '22 01:10

anosha_rehan