Programing

Rails : fields_for 색인 포함?

lottogame 2020. 8. 27. 08:06
반응형

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루프 에 있는지 알아야 합니다.


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

솔루션이 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] %>

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

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.indexRails 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

Checkout 부분 컬렉션 렌더링 . 템플릿이 배열을 반복하고 각 요소에 대한 하위 템플릿을 렌더링해야하는 것이 요구 사항 인 경우.

<%= 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됩니다.

도움이 되었기를 바랍니다.


I can't see a decent way to do this through the ways provided by Rails, at least not in -v3.2.14

@Sheharyar Naseer makes reference to the options hash which can be used to solve the problem but not as far as I can see in the way he seems to suggest.

I did this =>

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

or

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

In my case g.object_name returns a string like this "gallery_set[blog_posts_attributes][2]" for the third field rendered so I just match the index in that string and use it.


Actually a cooler (and maybe cleaner?) way to do it is to pass a lambda and call it to increment.

# /controller.rb
index = 0
@incrementer = -> { index += 1}

And the in the view

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

I know that this is a bit late but I recently had to do this you can get the index of the fields_for like this

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

I hope that this helps :)


If you want to have control over the indexes check out the index option

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

This will produce

<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">

If the form is submitted, params will include something like

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

I had to use the index option to get my multi-dropdowns to work. Good luck.


Added to 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 %>

참고URL : https://stackoverflow.com/questions/4853373/rails-fields-for-with-index

반응형