Rails 4错误:无法写入未知属性`html'

时间:2013-09-23 01:11:12

标签: ruby-on-rails ruby-on-rails-4

尝试设置基本的Rails 4应用程序用于学习目的时遇到错误,请耐心等待!我正在尝试创建一个应用程序来创建和显示自定义Web表单。我有一个Form模型,它有很多字段。我正在努力让视图工作,这将允许我创建一个附加到特定表单的新Field记录:

class Form < ActiveRecord::Base    
    has_many :fields    
end

class Field < ActiveRecord::Base
    belongs_to :form
end

在我的Field索引视图中,我相信我已经设置为正确显示特定表单的字段(通过像/ forms / 1 / fields这样的url),我有一个链接:

<%= link_to 'New Field', new_form_field_path(@form) %>

fields / new.html.erb文件包含:

<h1>New field</h1>
<%= render :partial => 'form', :form => @form, :field => @field %>

字段/ _form.html.erb的开头如下:

<%= form_for(@form, @field) do |f| %>

fields_controller.rb定义了此方法:

def new
  @form = Form.find(params[:form_id]) #unsure if this is necessary/correct, but its presence doesn't effect the error i'm getting
  @field = Field.new
end

已创建ID为1的表单。看起来/ forms / 1 / fields看起来好了。但是,当我单击“新建字段”链接,它将我带到/ forms / 1 / fields / new时,我收到此错误:

Showing /home/moskie/Projects/FormBuilder/app/views/fields/_form.html.erb where line #1 raised:

can't write unknown attribute `html'
Extracted source (around line #1):

  <%= form_for(@form, @field) do |f| %>
    <% if @field.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@field.errors.count, "error") %> prohibited this field from being saved:</h2>

Trace of template inclusion: app/views/fields/new.html.erb

Rails.root: /home/moskie/Projects/FormBuilder

Application Trace | Framework Trace | Full Trace
app/views/fields/_form.html.erb:1:in `_app_views_fields__form_html_erb___1866877160086017450_70350628427620'
app/views/fields/new.html.erb:3:in `_app_views_fields_new_html_erb___1515443138224133845_70350627074400'
Request

Parameters:

{"form_id"=>"1"}

我对此错误告诉我的内容感到非常困惑,所以我无法弄清楚我在这里做错了什么。谁能帮我吗?感谢。

1 个答案:

答案 0 :(得分:27)

知道了。 _form.html.erb字段局部视图中对form_for的调用需要方括号,而不是括号。在这种情况下,该方法需要将两个对象的数组作为其第一个参数,而不是将两个对象分别传入:

<%= form_for [@form, @field] do |f| %>