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