我正在使用单表继承来管理不同类型的项目。
楷模:
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"}}
如何解决?