我正在构建具有has_many
,belongs_to
关系的嵌套字段,如下所示:
app/controllers/widgets_controller.rb
def new
@widget = Widget.new
3.times { @widget.gizmos.build }
end
app/views/widgets/_form.html.erb
<%= form_for @widget do |f| %>
...
<%= f.fields_for :gizmos do |b| %>
<%= render 'gizmo_fields', f: b %>
<% end -%>
...
<% end -%>
app/views/widgets/_gizmo_fields.html.erb
<%= f.label :name "Gizmo -NUMBER-" %>
<%= f.text_field :name %>
如何以编程方式确定gizmo
总数中widget.gizmos
的数量。这样每个输出看起来像:
Gizmo 1 |_____text_____|
Gizmo 2 |_____text_____|
Gizmo 3 |_____text_____|
我想避免的事情:
我已经知道的事情:
gizmo
f.object
的当前实例
f.object.widget
操作上访问new
,因为记录尚未保存答案 0 :(得分:1)
@widget
的关联数组中找到它的位置
<%= f.fields_for :gizmos do |b| %>
<%= render 'gizmo_fields', f: b, index: @widget.gizmos.index(b.object) + 1 %>
<% end -%>
app/views/widgets/_gizmo_fields.html.erb
<%= f.label :name "Gizmo #{index}" %>
<%= f.text_field :name %>
答案 1 :(得分:0)
我相信你的部分中有一个变量'PARTIAL_NAME_counter',即
gizmo_fields_counter
请参阅http://databasically.com/2009/04/09/rails-render-partial-counters-displaying-a-records-index/