用于NilClass的未定义方法`model_name':Class -NULL值?

时间:2012-01-25 17:32:58

标签: ruby-on-rails ruby

我的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,这就是它出现此错误的原因?

2 个答案:

答案 0 :(得分:2)

停止这样做:@create_post@new_post@show_post@edit_post等等......

开始这样做:@post

问题是您的@create_post操作中的对象名为create。如果模型无效,则您的创建操作正在调用render "new"。 “新”视图需要设置@new_post,而不是。{1}}。 @new_postnilform_for(nil)引发错误。您应该在每个方法中调用变量@post no gain 用于命名@create_post@new_post。它增加了无意义的混乱,在这种情况下,破坏了事物。

答案 1 :(得分:0)

我的猜测:您的表单是部分的(包含表单代码的文件从_开始),因此当您从create操作调用它时,变量@new_post是没有实例化,你得到错误。这就是rails scaffold生成的代码有效的原因:脚手架代码在@postnewcreateedit操作中命名变量update ,因此他们可以使用他们共享的部分@post中的变量_form

Anway,当你提出这样的问题时,如果你给人们更多的信息(例如使用的Rails的版本以及错误的两三行),那就更好了。