My Rails app is generating this error whenever validation aren’t met:
undefined method `model_name' for NilClass:Class
post_controller.rb:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@show_post = Post.find(params[:id])
end
def new
@new_post = Post.new
end
def create
@create_post = Post.new(params[:post])
if @create_post.save
redirect_to posts_path, :notice => "Your post was save"
else
render "new"
end
end
def edit
@edit_post = Post.find(params[:id])
end
def update
@update_post = Post.find(params[:id])
if @update_post.update_attributes(params[:post])
redirect_to posts_path , :notice => "YOUR POST has been update"
else
render "edit"
end
end
def destroy
@destroy_post = Post.find(params[:id])
@destroy_post.destroy
redirect_to posts_path, :notice => "You succressfuly delete #{@destroy_post}"
end
end
index.html.erb:
<h1>My blog</h1>
<% @posts.each do |post|%>
<h2><%= link_to post.title, post%></h2>
<p><%= post.content%></p>
<p>
<%= link_to "EDIT", edit_post_path(post)%>
<%= link_to "Delete", post ,:confirm => "Are you sure?" , :method => :delete%>
</p>
<hr>
<% end%>
<p>
<%= link_to "Add new post", new_post_path %>
</p>
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content
validates :title, :content, :presence => true
validates :title, :length => { :minimum => 2}
validates :title, :uniqueness =>true
end
The error is raised in the following context:
Extracted source (around line #2):
1: <h1>Add new post</h1>
2: <%= form_for @new_post do |form|%>
3: <p>
4: <%= form.label :title%><br />
5: <%= form.text_field :title%>
I don’t think I have a problem with my code? Or the value is just nil and that’s why it comes with this error?
Stop doing this:
@create_post,@new_post,@show_post,@edit_postetc, etc…Start doing this:
@post.The problem is that your object is called
@create_postin yourcreateaction. If the model is invalid, your create action is callingrender "new". The “new” view expects@new_postto be set, which it isn’t.@new_postisnil, andform_for(nil)is raising an error. You should just be calling the variable@postin every method, there is no gain for naming them@create_postor@new_post. It adds meaningless clutter and, in this case, breaks things.