Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails undefined method `each' for nil:NilClass

I'm following the tutorial found here. It's simple, and I've followed the instructions exactly to step 6.7. At this point, I get the error

undefined method `each' for nil:NilClass 

when I try to access index.html.erb on the rails server.

I know the database is working fine, because I can do everything mentioned in step 6.3, create new posts and show/edit/destroy them with absolutely no problems.

Specifically, the issue is with the line

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

and it's essentially claiming that @posts is nil.

I appreciate any help for this ROR newbie! Thanks.

index.html.erb

<h1>Hello, Rails!</h1>
<table>
  <tr>
    <th>Name</th>
    <th>Title</th>
    <th>Content</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @posts.each do |post| %>
  <tr>
    <td><%= post.name %></td>
    <td><%= post.title %></td>
    <td><%= post.content %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
                                     :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to "My Blog", posts_path %>

posts_controller.rb

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end
like image 511
Jonathan Hwa Avatar asked Oct 22 '12 16:10

Jonathan Hwa


1 Answers

In order for the views to work fine in Rails they must be inside the correct directory. This is one of the many implementations of the so called "Convention over Configuration" that Rails loves.

So, if you have a method index and this method is inside a controller named PostsController, you must have a view named index inside the directory views/posts/. This way, Rails will know that it have to render this view when a get to this method is processed.

About a good tutorial, I would recommend this one. It is extense and covers a lot of things that are not just related to Rails itself, like deploying on Heroku and a little CSS.

like image 176
Lucas Nogueira Avatar answered Nov 03 '22 06:11

Lucas Nogueira