Rails:包含带有fields_for表单助手的索引

时间:2010-03-12 13:36:23

标签: ruby-on-rails webforms

我正在尝试使用fields_for方法从一个表单构建两个模型。我的代码如下所示:

<% for scale in @event.scales %>
  <% f.fields_for "scale[]", scale do |scale_form| %>
    <p>
      Scale<br />
      <%= scale_form.label :name %>
      <%= scale_form.text_field :name %>
      <%= scale_form.label :price %>
      <%= scale_form.text_field :price %>
    </p>
  <% end %>
<% end %>

但遗憾的是输出html缺少比例尺的ID:

<p>
  Scale<br />
  <label for="event_scale__name">Name</label>
  <input id="event_scale__name" name="event[scale][][name]" size="30" type="text" />
  <label for="event_scale__price">Price</label>
  <input id="event_scale__price" name="event[scale][][price]" size="30" type="text" />
</p>

...

这是相应的控制器和型号:

class EventsController < ApplicationController
  ...

  def new
    @event = Event.new
    @providers = Provider.find(:all, :order => :name)
    3.times { @event.scales.build }
    respond_to do |format|
      format.html
    end
  end

  ...
end


class Event < ActiveRecord::Base
  has_many :scales

  ...
end

我做错了什么?

1 个答案:

答案 0 :(得分:3)

Fields_for 不是封闭表单对象的方法,因此将f.fields_for更改为fields_for