28

I am currently teaching myself some RoR and doing the tutorial, but adding some nicer layout and stuff with bootstrap and I am running into a problem which I cant figure out.

I am trying to do the validation part (http://guides.rubyonrails.org/getting_started.html#adding-some-validation), but when I use:

<% @post.errors.any? %>

I get this message:

undefined method `errors' for nil:NilClass
Extracted source (around line #9):
<legend><h1>Add Post</h1></legend>

<%= form_for :post, url: posts_path, html: {class: 'form-horizontal'} do |f| %>
      <% if @post.errors.any? %>
        <div id="errorExplanation">

Nothing works and I even copied and pasted the parts from the tutorial.

Here is the code for the view:

<p> </p>

<div class="span6"

<fieldset>
    <legend><h1>Add Post</h1></legend>

    <%= form_for :post, url: posts_path, html: {class: 'form-horizontal'} do |f| %>
          <% if @post.errors.any? %>
            <div id="errorExplanation">

                <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

                <ul>
                    <% @post.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                    <% end %>
                  </ul>
            </div>
  <% end %>
        <div class="control-group">
            <%= f.label :title, :class => 'control-label' %>
            <div class="controls">
                <%= f.text_field :title, :class => 'span4' %>
            </div>
        </div>

        <div class="control-group">
            <%= f.label :content, :class => 'control-label' %>
            <div class="controls">
                <%= f.text_area :content, :rows => '7', :class => 'input-block-level' %>
            </div>
        </div>

        <div class="form-actions">
            <%= f.submit "Add Post", :class => 'btn btn-success' %>
            <%= link_to "Cancel", posts_path, :class => 'btn', :style => 'float:right;' %>
        </div>
    <% end %>
</fieldset>

</div>

And my posts_controller:

class PostsController < ApplicationController

    def new
    end

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

        if @post.save
            redirect_to @post
        else
            render 'new'
        end
    end

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

    def index
        @posts = Post.order("created_at desc")
    end

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

end

What am I missing? Thanks in advance!

iblue
  • 29,609
  • 19
  • 89
  • 128
tomr
  • 1,134
  • 2
  • 10
  • 25

4 Answers4

72

You need to define @post in your new action too.

def new
  @post = Post.new
end

You're getting the NilClass error because @post has no value (it's nil) when you first load the form on the new action.

When you do the render :new in your create action there is no problem because it's using the @post you've defined at the top of create.

deefour
  • 34,974
  • 7
  • 97
  • 90
  • @Deefour Hi. I'm doing the same tutorial and get the same error in `5.12 Updating Posts`. The `@post` variable is defined in the new method and it keeps throwing this error. Can you help me out? – Demnogonis Sep 27 '13 at 01:32
  • I had the same problem. It's really confusing since the upper part of the tutorial don't explicitly mention that one must write .New in the New action. – DennyHiu Mar 04 '17 at 22:52
1

Update the create method in posts.controller.rb file with the below piece of code. It worked for me.

def create
  @post = Post.new(params[:post].permit(:title, :text))
  @post.save
  redirect_to @post
end
Sankumarsingh
  • 9,889
  • 11
  • 50
  • 74
Sunny
  • 11
  • 1
0

In your posts_controller, add this :

def new
  @post = Post.new
end 
Gourav Thakur
  • 231
  • 2
  • 3
  • 15
0

If you have made the changes to edit/create etc. and it still gives you ActionView::Template::Error (undefined method `errors' for nil:NilClass):

Try restarting rails server

I kept receiving the error even after correcting the files in articles_controller.rb

and still got the error. It was fixed after i restarted rails server.

Shane
  • 36
  • 1
  • 6