Rails:fields_for 带索引? [英] Rails: fields_for with index?
问题描述
是否有一种方法(或实现类似功能的方法)来执行 fields_for_with_index
?
Is there a method (or way to pull off similar functionality) to do a fields_for_with_index
?
示例:
<% f.fields_for_with_index :questions do |builder, index| %>
<%= render 'some_form', :f => builder, :i => index %>
<% end %>
被渲染的部分需要知道 fields_for
循环中的当前索引是什么.
That partial being rendered needs to know what the current index is in the fields_for
loop.
推荐答案
下面的答案是多年前发布的,现代方法见:https://stackoverflow.com/a/22640703/105403
The answer below was posted many years ago, for a modern approach see: https://stackoverflow.com/a/22640703/105403
这实际上是更好的方法,更密切地遵循 Rails 文档:
This would actually be a better approach, following Rails documentation more closely:
<% @questions.each.with_index do |question,index| %>
<% f.fields_for :questions, question do |fq| %>
# here you have both the 'question' object and the current 'index'
<% end %>
<% end %>
来自:http://railsapi.com/doc/rails-v3.0.4/classes/ActionView/Helpers/FormHelper.html#M006456
也可以指定要使用的实例:
It’s also possible to specify the instance to be used:
<%= form_for @person do |person_form| %>
...
<% @person.projects.each do |project| %>
<% if project.active? %>
<%= person_form.fields_for :projects, project do |project_fields| %>
Name: <%= project_fields.text_field :name %>
<% end %>
<% end %>
<% end %>
<% end %>
这篇关于Rails:fields_for 带索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!