当前位置:  开发笔记 > 编程语言 > 正文

STI和form_for问题

如何解决《STI和form_for问题》经验,为你挑选了2个好方法。

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

楷模:

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"}}

怎么解决?



1> EmFi..:

这是你问题的根源.这是将@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 %>


在Rails 3.1中,将form_for语句写为<%= form_for @project,:as =>:project do | f | %>

2> 小智..:

对于Rails 3

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

推荐阅读
coco2冰冰
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有