次の代わりに、カスタムフォームヘルパーを作成する方法はありますか?
special_field_tag :object, :method
私は次のようなことを達成できます:
form.special_field :method
次の代わりに、カスタムフォームヘルパーを作成する方法はありますか?
special_field_tag :object, :method
私は次のようなことを達成できます:
form.special_field :method
はい、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 によって作成されたインスタンス変数がいくつかあります。
通常のヘルパーと同じ方法で HTML 入力要素にこれらの属性を作成するために、field_id メソッドと field_name メソッドを書きました。Rails が使用するのと同じメソッドに結び付ける方法があると確信していますが、まだ見つけていません。 .
これらのヘルパー メソッドでできることには限りがあり、単純に文字列を返します。HTML のテーブル全体またはページ全体を 1 つで作成できますが、それには十分な理由が必要です。
このファイルは app/helpers フォルダーに追加する必要があります
@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 />