Ruby on Rails Guides にフォームビルダーをカスタマイズする方法が載っていたので試してみた。
# lib/labelling_form_builder.rb class LabellingFormBuilder < ActionView::Helpers::FormBuilder def text_field(attribute, options={}) label(attribute) + super end end
# config/application.rb module Demo class Application < Rails::Application ... config.autoload_paths += %W(#{config.root}/lib) end end
# app/views/users/_form.html.erb <%= form_for @user, builder: LabellingFormBuilder do |f| %> <div class="field"> <%= f.text_field :email %> </div> <div class="field"> <%= f.text_field :name %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
text_field しか呼び出していませんが、ちゃんとラベルも出力されています。
<div class="field"> <label for="user_email">Email</label> <input id="user_email" name="user[email]" type="text"> </div> <div class="field"> <label for="user_name">Name</label> <input id="user_name" name="user[name]" type="text"> </div>