Projects#new中的NoMethodError

时间:2009-11-22 21:43:23

标签: ruby-on-rails

我正在关注来自github的合金复杂形式的例子,试图学习嵌套的表格,我只是无法让这个东西起作用。 http://github.com/alloy/complex-form-examples

NoMethodError in Projects#new

Showing app/views/projects/_form.html.erb where line #13 raised:

You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.new_record?

Extracted source (around line #13):

10:   </p>
11:   
12:   <p>
13:     <% project_form.fields_for :author do |author_form| %>
14:       <%= author_form.label :name, "Author name:" %>
15:       <%= author_form.text_field :name %>
16:       

Trace of template inclusion: app/views/projects/new.html.erb

class Comment < ActiveRecord::Base
  belongs_to :post
end


class Post < ActiveRecord::Base
  validates_presence_of :name, :title  
  validates_length_of :title, :minimum => 5 
  has_many :comments
  has_many :tags

  accepts_nested_attributes_for :tags, :allow_destroy => :true ,  
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end

class Tag < ActiveRecord::Base
  belongs_to :post
end

有人有什么建议吗?我一直试图让嵌套表格全天工作,但我没有成功。

projectsController

class ProjectsController < ApplicationController
  def index
    @projects = Project.find(:all)
  end

  def show
    @project = Project.find(params[:id])
  end

  def new
    @project = Project.new
    @project.tasks.build
    @project.tags.build
  end

  def create
    @project = Project.new(params[:project])
    if @project.save
      flash[:notice] = "Successfully created project."
      redirect_to @project
    else
      render :action => 'new'
    end
  end

  def edit
    @project = Project.find(params[:id])
    # add an extra new record for debugging purposes
    @project.tasks.build
    @project.tags.build
  end

  def update
    @project = Project.find(params[:id])
    @project.attributes = params[:project]
    if @project.save
      flash[:notice] = "Successfully updated project."
      redirect_to @project
    else
      render :action => 'edit'
    end
  end

  def destroy
    @project = Project.find(params[:id])
    @project.destroy
    flash[:notice] = "Successfully destroyed project."
    redirect_to projects_url
  end
end

1 个答案:

答案 0 :(得分:3)

您的author_form需要作者才能使用。要么在第13行之前构建它:

<% @project.build_author unless @project.author %>
<% project_form.fields_for :author do |author_form| %>
  <%= author_form.label :name, "Author name:" %>
  <%= author_form.text_field :name %>

或者你在ProjectsController中构建它:

def new
  @project = Project.new
  @project.tasks.build
  @project.tags.build

  @project.build_author unless @project.author
end
顺便说一句,“@ project.build_author除非@ project.author”在复杂表单示例的原始文件中。您可能在编辑时删除了它。