fireld_error_proc でデフォルトの状態だとエラー時にinput要素の周りをdivで囲われてしまいます。
<div class="field_with_errors">
<input autofocus="autofocus" autocomplete="email" placeholder="email" type="email" value="" name="user[email]" id="user_email">
</div>
↑こんな感じ
その際に、divで囲うのではなく要素自体に特定のクラス名をつけたい時の書き方
追加手順
nokogiriをinstall
Gemfile
# nokogiri
# https://github.com/sparklemotion/nokogiri
gem 'nokogiri'
application.rbに以下を追加
config/application.rb
# Application class内に追加
config.action_view.field_error_proc = proc do |html_tag, _instance|
if html_tag.match?(/<(input|label|textarea|select)/)
html_field = Nokogiri::HTML::DocumentFragment.parse(html_tag)
html_field.children.add_class 'error'
html_field.to_s.html_safe
else
html_tag.html_safe
end
end
特定の要素だった場合、nokogiriで特定の文字列をパースしてadd_classをする
出力結果
<input autofocus="autofocus" autocomplete="email" class="error" placeholder="email" type="email" value="" name="user[email]" id="user_email">
参考