带有自定义rails的额外字段构建构建器

Dan*_*tep 6 ruby forms ruby-on-rails

我有一个自定义表单构建器,这个自定义构建器的原因之一是,对于每个表单,我需要包含一些额外的参数,我不想在我写的每个表单中明确地输入隐藏的字段标记.

for_for(@foo, :builder => MyBuilder) do |f|
  # stuff I shouldn't have to worry about
  # this should be put in all the time without me having to do it
  hidden_field_tag('extra', 'myextrainfo')

  # normal things I would put in
  f.text_field(:bar)
end
Run Code Online (Sandbox Code Playgroud)

我在自定义表单构建器中需要做什么,或者我可以覆盖什么或方法链以在表单中添加一些额外的隐藏内容(不添加URL参数)?

Veg*_*ger 5

这有点棘手(对Ruby/Rails来说是合理的新东西),但我找到了一个解决方案.把它放在一些帮助文件(或根据您的需要的其他位置).

module ActionView::Helpers::FormHelper
  def form_for_with_updated_code(record_or_name_or_array, *args, &proc)
    form_for_without_updated_code(record_or_name_or_array, *args) { |f|
       concat(hidden_field_tag('extra','info'))
       proc.call(f)
    }
  end
  alias_method_chain :form_for, :updated_code
end
Run Code Online (Sandbox Code Playgroud)

它会覆盖form_for方法并添加隐藏字段.您可以将代码添加到额外的个人选项中,例如*args使用参数填充隐藏字段extract_options!.