25

次の代わりに、カスタムフォームヘルパーを作成する方法はありますか?

special_field_tag :object, :method

私は次のようなことを達成できます:

form.special_field :method
4

3 に答える 3

48

はい、FormBuilder クラスに追加して、form_for に渡されたオブジェクトにアクセスできます。日付、時刻、測定値など、多くのことに対してこれを行いました。例を次に示します。

class ActionView::Helpers::FormBuilder
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::FormTagHelper
  include ActionView::Helpers::FormOptionsHelper
  include ActionView::Helpers::CaptureHelper
  include ActionView::Helpers::AssetTagHelper

  # Accepts an int and displays a smiley based on >, <, or = 0
  def smile_tag(method, options = {})
    value = @object.nil? ? 0 : @object.send(method).to_i
    options[:id] = field_id(method,options[:index])
    smiley = ":-|"
    if value > 0
      smiley = ":-)"
    elsif smiley < 0
       smiley = ":-("
    end
    return text_field_tag(field_name(method,options[:index]),options) + smiley
  end

  def field_name(label,index=nil)
    output = index ? "[#{index}]" : ''
    return @object_name + output + "[#{label}]"
  end

  def field_id(label,index=nil)
    output = index ? "_#{index}" : ''
    return @object_name + output + "_#{label}"
  end

end

次のように使用できます。

<% form_for @quiz do |f| %>
  <%= f.smile_tag(:score) %>
<% end %>

これらのヘルパー メソッドでアクセスできる、Rails によって作成されたインスタンス変数がいくつかあります。

  • @object - フォームで指定されたモデル オブジェクト
  • @object_name - オブジェクトのクラス名
  • @template - ActionView のインスタンスだと思います。テンプレートのメソッドを呼び出すことで、追加したすべてのインクルードをバイパスできる可能性があります。まだ試していません。
  • @options - form_for 呼び出しによって作成されたときに FormBuilder に渡されるオプション

通常のヘルパーと同じ方法で HTML 入力要素にこれらの属性を作成するために、field_id メソッドと field_name メソッドを書きました。Rails が使用するのと同じメソッドに結び付ける方法があると確信していますが、まだ見つけていません。 .

これらのヘルパー メソッドでできることには限りがあり、単純に文字列を返します。HTML のテーブル全体またはページ全体を 1 つで作成できますが、それには十分な理由が必要です。

このファイルは app/helpers フォルダーに追加する必要があります

于 2010-04-12T21:54:35.447 に答える
7

@Tilendor、ポインタをありがとう。enum_select以下は、 Rails 4.1 列挙型を使用して select タグのオプションを自動的に入力するフォーム タグ ヘルパーの例です。

# helpers/application_helper.rb
module ApplicationHelper
  class ActionView::Helpers::FormBuilder
    # http://stackoverflow.com/a/2625727/1935918
    include ActionView::Helpers::FormTagHelper
    include ActionView::Helpers::FormOptionsHelper
    def enum_select(name, options = {})
      # select_tag "company[time_zone]", options_for_select(Company.time_zones
      #   .map { |value| [value[0].titleize, value[0]] }, selected: company.time_zone)
      select_tag @object_name + "[#{name}]", options_for_select(@object.class.send(name.to_s.pluralize)
        .map { |value| [value[0].titleize, value[0]] }, selected: @object.send(name))
    end
  end
end

最もトリッキーな構造は@object.class.send(name.to_s.pluralize)、利用可能な値のハッシュを生成するものです (例: Company.time_zones)。入れるとhelpers/application_helper.rb自動的に利用可能になります。次のように使用されます。

<%= f.label :billing_status %>:
<%= f.enum_select :billing_status %><br />
于 2014-07-25T04:25:30.997 に答える