【问题标题】:Extra fields with custom rails form builder带有自定义导轨表单构建器的额外字段
【发布时间】:2010-01-21 18:15:42
【问题描述】:

我有一个自定义表单构建器,这个自定义构建器的一个原因是,对于每个表单,我都需要包含一些额外的参数,我不想在每个表单中使用隐藏字段标签显式放入这些参数。写。

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

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

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    这有点棘手(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
    

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

    【讨论】:

    • 非常好。充满胜利。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-04-21
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多