. Advertisement .
..3..
. Advertisement .
..4..
As advised, I used some code samples in another forum, but it could not improve the problem. My question is the “undefined method `each’ for nil:nilclass” in programs – How to solve it?
The command line is:
<th>Text</th>
</tr>
<% @posts.each do |post| %>
and the result:
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| %>
======================================================
What does the message mean? Can you advise me to fix it? If you have other better answers, leave them in the answer box below.
The cause: This problem occurs because you’re calling each method on something here(
@posts
) which is nil. This indicates that you haven’t defined it in your controller.Solution: To solve this error,
@posts
must be defined in your posts controller.This error can be explained in more detail if you are unable to identify it.
This error indicates that you are calling each method here (@posts), which is null. This means that you have not defined it in the controller. It is complaining about an undefined method for nil because you didn’t define the class.
You should always double-check the instance variable you are calling from your view. To make it accessible from views, you will need to create that controller.
This error can also be thrown if you try to call a private method from your controller.