field_with_errorsをカスタマイズしたい
アプリ全体に適用する
config/application.rb
config.action_view.field_error_proc = Proc.new do |html_tag, instance|
%Q(<span class="has-error">#{html_tag}</span>).html_safe
end
参考 : Railsのバリデーションエラーで、「field_with_errors」によるレイアウト崩れを防ぐ
ページ単位
app/hoge_helper.rbあたりに書く。
app/hoge_helper.rb
module SportsHelper
ActionView::Base.field_error_proc = proc do |html_tag|
%(<span class="has-error">#{html_tag}</span>).html_safe
end
end
ただしこれだと、html_safeは使うなとRuboCopに怒られる。
RuboCop: Tagging a string as html safe may be a security risk. [Rails/OutputSafety]
[Rails/OutputSafety]を回避する書き方
app/hoge_helper.rb
module SportsHelper
ActionView::Base.field_error_proc = proc do |html_tag|
v = ActionView::Base.new
v.content_tag(:span, html_tag, class: 'has-error')
end
end