Rails - increment variable in fields_for loop

I'm hoping this is a simple question - I have the following helper code:

module ApplicationHelper

  def add_feature_fields(feature_types, object_form_builder, actions_visible)
    feature_types.length.times {object_form_builder.object.features.build}
    i = 0
    fields = object_form_builder.fields_for :features do |features_builder|
      render :partial => "features/fixed_feature", :locals => {:feature => features_builder, :fixed_feature_type => feature_types[i], :form_actions_visible => actions_visible}
      i = i + 1
    end
  end
end

The code is working as expected, except for the line i = i + 1. For some reason, this seems to be breaking the loop, and nothing is rendered. Evidently, I am doing this wrong somehow - perhaps fields_for is not a normal loop?

How can I increment i by 1 each time the loop runs?

Answers


I'm not sure about the below code, but something around this should work and fix the issue. Give a try

object_form_builder.each.with_index do |builder,index|
  object_form_builder.fields_for :features, builder do |feature_builder|
      render :partial => "features/fixed_feature", :locals => {:feature => features_builder, :fixed_feature_type => feature_types[i], :form_actions_visible => actions_visible}
  end
end

I was able to get this working by doing the following:

module ApplicationHelper

  def add_feature_fields(feature_types, object_form_builder, actions_visible)
    feature_types.length.times {object_form_builder.object.features.build}
    i = -1
    object_form_builder.fields_for :features do |features_builder|
      i = i + 1
      render :partial => "features/fixed_feature", :locals => {:feature => features_builder, :fixed_feature_type => feature_types[i], :form_actions_visible => actions_visible}
    end
  end
end

I believe what was happening was that when I did i = i + 1 after I called render, the return value was the iterator and not render (since the method returns the last value).


Need Your Help

EasyMock 2.5 doesn't work for more than one argument capture

java mockito easymock

Exception appear when I try to capture more than one value using EasyMock.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.