Rails - 在fields_for循环中增加变量

时间:2012-08-23 08:49:20

标签: ruby-on-rails ruby ruby-on-rails-3

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

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?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

我相信发生的事情是当我在调用render后执行i = i + 1时,返回值是迭代器而不是渲染(因为该方法返回最后一个值)。