user2698988
user2698988

Reputation: 359

Why Am I Receiving this NoMethodError?

I am working through a Ruby on Rails tutorial for creating a blog and I have received this error when I go to bring up the page in my localhost:3000 address:

'undefined method `each' for nil:NilClass'

My Controller:

class PostsController < ApplicationController

def new
end

def create
  @post = Post.new(params[:post].permit(:title, :text))

  @post.save
  redirect_to @post
end

def show
  @post = Post.find(params[:id])
end

private

def post_params
  params.require(:post).permit(:title, :text)
 end

def index
  @posts = Post.all 
end
end

My View File:

<h1>Listing posts</h1>


    <table>
      <tr>
        <th>Title</th>
        <th>Text</th>
      </tr>

      <% @posts.each do |post| %>
        <tr>
          <td><%= post.title %></td>
          <td><%= post.text %></td>
        </tr>
      <% end %>
    </table>

Can someone help me out?

Upvotes: 0

Views: 47

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51191

Because your PostsController#index method is private, so its code doesn't run when you enter /posts, so @posts instance variable remains nil.

Move it to public section:

class PostsController < ApplicationController

  def index
    @posts = Post.all 
  end

  def new
  end

  def create
    @post = Post.new(params[:post].permit(:title, :text))

    @post.save
    redirect_to @post
  end

  def show
    @post = Post.find(params[:id])
  end

  private

    def post_params
      params.require(:post).permit(:title, :text)
    end
end

Upvotes: 1

hedgesky
hedgesky

Reputation: 3311

You should move index action away from private section.

Upvotes: 1

Related Questions