4

だから私はこのヘルパーメソッドを持っていますよね?

def table_form_field(name_or_options = nil, *args, &block)
  # ...
  render :partial => "snippets/table_form_field", :locals => options
end

フォームビルダーで使用したい場合を除いて、それは素晴らしいことです。そのためには、次のように呼び出す必要があります。

table_form_field(:foo, :form_builder => f) do |name|
  f.text_field name
end

:form_builder を手動で指定しなければならないのは面倒です。したがって、私の目標はActionView::Helpers::FormBuilder、次のように新しいメソッドを拡張して追加することです。

class ActionView::Helpers::FormBuilder
  def table_form_field(name_or_options, options, &block)
    if name_or_options.is_a?(Hash)
      name_or_options[:form_builder] = self
    else
      options[:form_builder] = self
    end

    # But... how can I call the helper?
    # Hmm, I'll try this:

    klass = Class.new do
      include ApplicationHelper
    end

    klass.new.send(:table_form_field, name_or_options, options, &block)

    # Thank you, Mario, but your princess is in another castle!
    #
    # Basically, this tries to call render, and for obvious
    # reasons, klass doesn't know how to render.
    #
    # So... what do I do?
  end
end
4

1 に答える 1

4

@templateフォームビルダー内から呼び出されたインスタンス変数にアクセスできるためtable_form_field@template変数を呼び出すだけです。

たとえば、ActionView::Helpers::FormBuilder から継承するカスタム フォーム ビルダーを作成します。

class MyFormBuilder < ActionView::Helpers::FormBuilder
  def table_form_field(*attrs, &block)
    @template.table_form_field(*attrs, &block)
  end
end

次に、 form_for で、カスタムフォームビルダーを使用するように指示できます

<%= form_for @myobject, :builder => MyFormBuilder do |f| %>
  <%= f.table_form_field :myfield do %>
  <% end %>
<%= end %>
于 2011-08-30T16:12:44.233 に答える