Rails: fields_for с индексом?
Есть ли способ (или способ снять аналогичную функциональность), чтобы сделать fields_for_with_index
?
Пример:
<% f.fields_for_with_index :questions do |builder, index| %>
<%= render 'some_form', :f => builder, :i => index %>
<% end %>
Частичное визуализация должно знать, что текущий индекс находится в цикле fields_for
.
Ответы
Ответ 1
На самом деле это был бы более эффективный подход, следующий за документацией Rails:
<% @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
Можно также указать экземпляр, который будет использоваться:
<%= 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 %>
Ответ 2
Ответ довольно прост, так как решение предоставляется в Rails. Вы можете использовать параметры f.options
. Итак, внутри вашего рендеринга _some_form.html.erb
,
Индекс может быть доступен:
<%= f.options[:child_index] %>
Вам не нужно ничего делать.
Обновление: похоже, мой ответ был недостаточно ясным.
Оригинальный HTML файл:
<!-- Main ERB File -->
<% f.fields_for :questions do |builder| %>
<%= render 'some_form', :f => builder %>
<% end %>
Представленная подформа:
<!-- _some_form.html.erb -->
<%= f.options[:child_index] %>
Ответ 3
В Rails 4.0.2 теперь в объект FormBuilder включен индекс:
http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormHelper/fields_for
Например:
<%= form_for @person do |person_form| %>
...
<%= person_form.fields_for :projects do |project_fields| %>
Project #<%= project_fields.index %>
...
<% end %>
...
<% end %>
Ответ 4
Для рельсов 4+
<%= form_for @person do |person_form| %>
<%= person_form.fields_for :projects do |project_fields| %>
<%= project_fields.index %>
<% end %>
<% end %>
Поддержка Monkey Patch For Rails 3
Чтобы заставить f.index
работать в Rails 3, вам нужно добавить патч обезьяны в инициализаторы ваших проектов, чтобы добавить эту функциональность в fields_for
# config/initializers/fields_for_index_patch.rb
module ActionView
module Helpers
class FormBuilder
def index
@options[:index] || @options[:child_index]
end
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
fields_options[:builder] ||= options[:builder]
fields_options[:parent_builder] = self
fields_options[:namespace] = options[:namespace]
case record_name
when String, Symbol
if nested_attributes_association?(record_name)
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
end
else
record_object = record_name.is_a?(Array) ? record_name.last : record_name
record_name = ActiveModel::Naming.param_key(record_object)
end
index = if options.has_key?(:index)
options[:index]
elsif defined?(@auto_index)
self.object_name = @object_name.to_s.sub(/\[\]$/,"")
@auto_index
end
record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]"
fields_options[:child_index] = index
@template.fields_for(record_name, record_object, fields_options, &block)
end
def fields_for_with_nested_attributes(association_name, association, options, block)
name = "#{object_name}[#{association_name}_attributes]"
association = convert_to_model(association)
if association.respond_to?(:persisted?)
association = [association] if @object.send(association_name).is_a?(Array)
elsif !association.respond_to?(:to_ary)
association = @object.send(association_name)
end
if association.respond_to?(:to_ary)
explicit_child_index = options[:child_index]
output = ActiveSupport::SafeBuffer.new
association.each do |child|
options[:child_index] = nested_child_index(name) unless explicit_child_index
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
end
output
elsif association
fields_for_nested_model(name, association, options, block)
end
end
end
end
end
Ответ 5
Оформить заказ Предоставление коллекции частичных файлов. Если ваше требование состоит в том, что шаблону необходимо перебирать по массиву и отображать дополнительный шаблон для каждого из элементов.
<%= f.fields_for @parent.children do |children_form| %>
<%= render :partial => 'children', :collection => @parent.children,
:locals => { :f => children_form } %>
<% end %>
Это отобразит "_children.erb" и передаст локальную переменную "children" в шаблон для отображения. Счетчик итераций автоматически будет доступен шаблону с именем формы partial_name_counter
. В случае примера выше шаблон будет отправлен children_counter
.
Надеюсь, что это поможет.
Ответ 6
Я не вижу достойного способа сделать это с помощью способов, предоставляемых Rails, по крайней мере, не в -v3.2.14
@Sheharyar Naseer ссылается на хэш-параметры, которые могут быть использованы для решения проблемы, но не настолько, насколько я могу видеть в том, как он, кажется, предлагает.
Я сделал это = >
<%= f.fields_for :blog_posts, {:index => 0} do |g| %>
<%= g.label :gallery_sets_id, "Position #{g.options[:index]}" %>
<%= g.select :gallery_sets_id, @posts.collect { |p| [p.title, p.id] } %>
<%# g.options[:index] += 1 %>
<% end %>
или
<%= f.fields_for :blog_posts do |g| %>
<%= g.label :gallery_sets_id, "Position #{g.object_name.match(/(\d+)]/)[1]}" %>
<%= g.select :gallery_sets_id, @posts.collect { |p| [p.title, p.id] } %>
<% end %>
В моем случае g.object_name
возвращает строку, подобную этой "gallery_set[blog_posts_attributes][2]"
для третьего визуализированного поля, поэтому я просто сопоставляю индекс в этой строке и использую ее.
На самом деле кулер (и, возможно, более чистый?) способ сделать это - передать лямбду и вызвать ее для увеличения.
# /controller.rb
index = 0
@incrementer = -> { index += 1}
И в представлении
<%= f.fields_for :blog_posts do |g| %>
<%= g.label :gallery_sets_id, "Position #{@incrementer.call}" %>
<%= g.select :gallery_sets_id, @posts.collect { |p| [p.title, p.id] } %>
<% end %>
Ответ 7
Я знаю, что это немного поздно, но я недавно должен был сделать это, вы можете получить индекс полей для этого
<% f.fields_for :questions do |builder| %>
<%= render 'some_form', :f => builder, :i => builder.options[:child_index] %>
<% end %>
Я надеюсь, что это поможет:)
Ответ 8
Если вы хотите контролировать индексы, проверьте параметр index
<%= f.fields_for :other_things_attributes, @thing.other_things.build do |ff| %>
<%= ff.select :days, ['Mon', 'Tues', 'Wed'], index: 2 %>
<%= ff.hidden_field :special_attribute, 24, index: "boi" %>
<%= end =>
Это приведет к созданию
<select name="thing[other_things_attributes][2][days]" id="thing_other_things_attributes_7_days">
<option value="Mon">Mon</option>
<option value="Tues">Tues</option>
<option value="Wed">Wed</option>
</select>
<input type="hidden" value="24" name="thing[other_things_attributes][boi][special_attribute]" id="thing_other_things_attributes_boi_special_attribute">
Если форма отправлена, параметры будут содержать что-то вроде
{
"thing" => {
"other_things_attributes" => {
"2" => {
"days" => "Mon"
},
"boi" => {
"special_attribute" => "24"
}
}
}
Мне пришлось использовать опцию index, чтобы работать с несколькими выпадающими списками. Удачи.
Ответ 9
Добавлено в fields_for child_index: 0
<%= form_for @person do |person_form| %>
<%= person_form.fields_for :projects, child_index: 0 do |project_fields| %>
<%= project_fields.index %>
<% end %>
<% end %>