每当验证不满足时,我的Rails应用程序都会生成此错误:
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
错误是在以下上下文中引发的:
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%>
我想我的代码没有问题吧?或者值只是nil
,这就是为什么它会出现这个错误?
停止执行以下操作:@create_post
、@new_post
、@show_post
、@edit_post
等…
开始这样做:@post
。
问题是您的对象在create
操作中被称为@create_post
。如果模型无效,则创建操作将调用render "new"
。"new"视图期望设置@new_post
,但事实并非如此。@new_post
是nil
,并且form_for(nil)
正在引发错误。您应该只在每个方法中调用变量@post
,将它们命名为@create_post
或@new_post
没有任何好处。它增加了无意义的混乱,在这种情况下,还会破坏事物。
我的猜测:您的表单是分部的(包含表单代码的文件以_
开头),所以当您从create
操作调用它时,变量@new_post
没有实例化,您会得到错误。这就是rails scaffold
生成的代码工作的原因:脚手架代码在new
、create
、edit
和update
操作中命名变量@post
,因此它们可以在共享的部分_form
中使用变量@post
。
顺便说一句,当你提出这样的问题时,最好给人们更多的信息(例如,使用的Rails版本和两三行错误)。