0

我希望这是一个简单的问题 - 我有以下帮助代码:

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

代码按预期工作,除了行i = i + 1。出于某种原因,这似乎打破了循环,并且没有渲染任何内容。显然,我以某种方式做错了——也许 fields_for 不是一个正常的循环?

每次循环运行时,如何将 i 增加 1?

4

2 回答 2

0

我不确定下面的代码,但围绕这个的东西应该可以解决问题。试一下

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
于 2012-08-23T09:12:04.973 回答
0

我能够通过执行以下操作来完成此工作:


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 = i + 1在调用渲染后执行此操作时,返回值是迭代器而不是渲染(因为该方法返回最后一个值)。

于 2012-08-23T10:12:36.900 回答