15

我正在使用单表继承来管理不同类型的项目。

楷模:

class Project < ActiveRecord::Base
end

class SiteDesign < Project
end

class TechDesign < Project
end

从 projects_controller 编辑操作:

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

查看edit.html.erb:

<% form_for(@project, :url => {:controller => "projects",:action => "update"}) do |f| %>
    ...
    <%= submit_tag 'Update' %>
<% end %>

projects_controller 的更新操作:

def update
    @project = Project.find(params[:id])
    respond_to do |format|
      if @project.update_attributes(params[:project])
        @project.type = params[:project][:type]
        @project.save
        flash[:notice] = 'Project was successfully updated.'
        format.html { redirect_to(@project) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @project.errors, :status => :unprocessable_entity }
      end
    end
  end

然后我在编辑视图上对 TechDesign 条目进行一些编辑并得到错误:

NoMethodError in ProjectsController#update

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.[]

在参数中,很明显,我有 tech_design 参数,而不是项目参数名称:

{"commit"=>"Update",
 "_method"=>"put",
 "authenticity_token"=>"pd9Mf7VBw+dv9MGWphe6BYwGDRJHEJ1x0RrG9hzirs8=",
 "id"=>"15",
 "tech_design"=>{"name"=>"ech",
 "concept"=>"efds",
 "type"=>"TechDesign",
 "client_id"=>"41",
 "description"=>"tech"}}

如何解决?

4

4 回答 4

26

这是您的问题的根源。这是将 @project 设置为 TechDesign 对象的实例。

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

您可以通过在 form_for 调用中为名称指定 :project 来确保事情按照您想要的方式进行。

<% form_for(:project, @project, :url => {:controller => "projects",:action => "update"}) do |f| %>
    ...
    <%= submit_tag 'Update' %>
<% end %>
于 2009-10-16T16:20:01.137 回答
6

对于 Rails 3

<% form_for(@project, :as => :project, :url => {:controller => "projects",:action => "update"}) do |f| %>
...
   <%= submit_tag 'Update' %>
<% end %>
于 2012-09-21T15:03:56.957 回答
2

随机说明:如果您使用单表继承 (STI) 并且忘记从子类定义中删除初始化方法,您将获得类似的“当您没有预料到它时出现 nil 对象”异常。

例如:

class Parent < ActiveRecord::Base
end

class Child < Parent
  def initialize
    # you MUST call *super* here or get rid of the initialize block
  end
end

就我而言,我使用我的 IDE 创建子类,并且 IDE 创建了初始化方法。让我永远追查...

于 2010-06-18T14:26:12.880 回答
2

对于 Rails 4,我已经确认唯一似乎对我有用的是明确指定 URL 和 AS 参数:

<% form_for(@project, as: :project, url: {controller: :projects, action: :update}) do |f| %>
    ...
<% end %>

在我看来很难看!

于 2015-05-20T18:04:49.280 回答