STI和form_for问题 [英] STI and form_for problem

查看:97
本文介绍了STI和form_for问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Single Table Inheritance for managing different types of projects.

型号:

class Project < ActiveRecord::Base
end

class SiteDesign < Project
end

class TechDesign < Project
end

从projects_controller编辑动作:

Edit action from projects_controller:

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

查看edit.html.erb:

View edit.html.erb:

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

更新projects_controller的操作:

Update action of 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条目进行一些编辑并得到错误:

Then i do some edits of TechDesign entry on edit view and get error:

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而不是项目参数名称 参数:

In parametrs it is obvious that instead of project parameter name i have tech_design Parameters:

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

如何解决?

推荐答案

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

Here's the source of your problem. This is setting @project as an instance of a TechDesign object.

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

您可以通过在form_for调用中为名称指定:project来确保一切正常.

You can ensure things work the way you want by specifying :project for a name in the form_for call.

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

这篇关于STI和form_for问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆