Rails:fields_for带索引?

时间:2011-01-31 16:32:22

标签: ruby-on-rails loops 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循环中当前索引的内容。

9 个答案:

答案 0 :(得分:149)

答案非常简单,因为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] %>

答案 1 :(得分:86)

这实际上是一种更好的方法,更紧密地遵循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 :(得分:86)

从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 %>

答案 3 :(得分:13)

对于Rails 4 +

<%= form_for @person do |person_form| %>
  <%= person_form.fields_for :projects do |project_fields| %>
    <%= project_fields.index %>
  <% end %>
<% end %>

支持Rails 3的Monkey Patch

要让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

答案 4 :(得分:7)

结帐Rendering a collection of partials。如果您的要求是模板需要遍历数组并为每个元素渲染子模板。

<%= 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

希望这有帮助。

答案 5 :(得分:6)

我无法通过Rails提供的方式看到这样做的好方法,至少在-v3.2.14

中没有

@Sheharyar Naseer引用了可用于解决问题的选项哈希,但没有达到我所能看到的方式。

我做了这个=&gt;     

<%= 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]"这样的字符串,所以我只是匹配该字符串中的索引并使用它。


实际上,冷却器(可能更干净?)的方法是传递一个lambda并调用它来递增。

# /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 %>

答案 6 :(得分:1)

我知道这有点晚了但是我最近不得不这样做你可以像这样得到fields_for的索引

<% f.fields_for :questions do |builder| %>
  <%= render 'some_form', :f => builder, :i => builder.options[:child_index] %>
<% end %>

我希望这会有所帮助:)

答案 7 :(得分:1)

已添加到fields_for child_index:0

const _products = [
{"id": 1, "title": "iPad 4 Mini", "price": 500.01, "inventory": 2},
{"id": 2, "title": "H&M T-Shirt White", "price": 10.99, 
"inventory": 10},
{"id": 3, "title": "Charli XCX - Sucker CD", "price": 19.99, 
"inventory": 5}
  ]

export default {
getProducts (cb) {
    setTimeout(() => cb(_products), 100)
   },
buyProducts (products, cb, errorCb) {
    setTimeout(() => {
    // simulate random checkout failure.
    (Math.random() > 0.5 || 
navigator.userAgent.indexOf('PhantomJS') > -1)
    ? cb()
    : errorCb()
}, 100)
 }
}

答案 8 :(得分:0)

如果您想控制索引,请查看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">

如果表单已提交,params将包含类似

的内容
{
  "thing" => {
  "other_things_attributes" => {
    "2" => {
      "days" => "Mon"
    },
    "boi" => {
      "special_attribute" => "24"
    }
  }
}

我不得不使用索引选项让我的多下拉列表工作。祝你好运。