I am trying to create a Rails blog app with this tutorial
I am stuck on the step that validates that the fields a user enters are not empty. However, if I try to pass empty fields, I get this error:
NoMethodError in Posts#create Showing C:/Users/irowe/Documents/GitHub/Rails-Blog/blog/app/views/posts/new.html.erb where line #3 raised: undefined method `errors' for nil:NilClass Here is my post controller:
class PostsController < ApplicationController def index @posts = Post.all.order(created_at: :desc) end def show end def new @post = Post.new end def create p = Post.new(title: params[:post][:title], content: params[:post][:content]) if p.save flash[:notice] = 'Successfully created a new post!' redirect_to root_path else flash[:alert] = 'Something went awry...' render :new end end end and my "new post" view
<h1>New Post</h1> <ul> <% @post.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> <%= form_for @post, url: create_post_path do |f| %> <%= f.text_field :title %> <br /> <%= f.text_area :content %> <br /> <%= f.submit %> <% end %> And the post model
class Post < ActiveRecord::Base validates_presence_of :title validates_presence_of :content before_validation :preval private def preval if self.title self.title = self.title.strip end if self.content self.content = self.content.strip end end end I have seen other answers like this but they just recommend to make sure post is not nil , which I have made sure it isn't. Any ideas on how to make sure the validation woks? I am totally new to Rails.