【问题标题】:Handling forms with Single Table Inheritance使用单表继承处理表单
【发布时间】:2011-03-28 17:20:30
【问题描述】:

我的个人资料编辑视图中有一个以该行开头的表单:

<% form_for @profile, :html => { :multipart => true } do |f| %>

Profile 进行单表继承,两个子类是 Profile::Artist 和 Profile::Listener。

当我尝试访问配置文件的编辑视图时,我收到此错误:

NoMethodError in Profiles#edit

Showing /rubyprograms/dreamstill/app/views/profiles/edit.html.erb where line #1 raised:

undefined method `profile_artist_path' for #<#<Class:0x103359a18>:0x1033560c0>

其中第 1 行是我在上面发布的表单的代码行。我该如何解决这个错误?

更新:

我将此代码添加到我的个人资料模型中:

def self.inherited(child)
  child.instance_eval do
    def model_name
      Vehicle.model_name
    end
  end
  super
end

现在我的错误变成了:

NameError in Profiles#edit

Showing /rubyprograms/dreamstill/app/views/profiles/edit.html.erb where line #1 raised:

uninitialized constant Profile::Vehicle

更新 2:

我将表格的第一行改为:

<% form_for(:profile, @profile, :url => {:controller => "profiles", :action => "update"}, :html => { :multipart => true }) do |f| %>

和提交按钮到&lt;%= f.submit :profile %&gt;

现在我只是得到一个路由错误...

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 routing single-table-inheritance


【解决方案1】:

不是Vehile,而是Profile

def self.inherited(child)
  child.instance_eval do
    def model_name
      Profile.model_name
    end
  end
  super
end

def self.model_name
  name = "profile"
  name.instance_eval do
    def plural;   pluralize;   end
    def singular; singularize; end
    def i18n_key; singularize; end
    def human(*args); singularize; end
  end
  return name
end

更新

实际问题出在形式上。你应该添加:method =&gt; :put

<%= form_for(@profile, :html => { :multipart => true, :method => :put }) do |f| %>

【讨论】:

  • nah Profile 是父类,而不是 Artist
  • 顺便说一下我用的是普通的第二种方法
  • 好的,看看我发布的新表单代码......它似乎工作除了更新表单时出现路由错误......
  • 如果您能提供我应该添加的路线示例,我将不胜感激。
  • 没什么大不了的,但您应该使用&lt;%= form_for 而不是&lt;% form_for。关于您的问题:您不需要指定任何新路线。尝试使用我的第二种方法。删除您的 self.inherited 并添加 self.model_name 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2010-09-17
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多