I am following http://guides.rubyonrails.org/getting_started.html and trying to add validation to text field. My class:
class Article < ActiveRecord::Base
validates :title, presence: true, length: { minimum: 5 }
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
My new.html.erb file:
<%= form_for :article, url: articles_path do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
And when I try to add new article I open http://localhost:3000/articles/new but instead of the form I see error undefined method errors' for nil:NilClass
because of the error in this line <% if @article.errors.any? %>
What am I missing here. Looks like @article
is being validated before created? How can I fix it?