Ruby on Rails 3.xでバリデーションの表示を変える

Ruby on Rails 3.xでバリデーションのとき、バリデーションにひっかかったところを教えてくれる機能がある。
ところが、CSSを使用していると画面がずれてしまうことがあった。とくに、JQuery Mobileとの相性はよくなくて、JQuery Mobileは簡単な設定で画面を作るのでCSSをいじってもどうしようもなくなる。

そこでエラー時の表示を変える方法があった。Ruby on Railsでは標準ではエラーとなるときに、field_with_errorsというdivタグで囲んでしまう。そこをinputやselectタグをdivタグで囲まずにクラスでfield_with_errorsを付ける方法である。
(別の方法としては、divタグでは囲まずにspanタグで囲むという方法もあるので併記してみた)
あとは、cssでエラー時の表示を定義するだけである。
これだけのために、のべで数日間という時間を費やしてしまった。

config/application.rb
[ruby]
module xxxxxx
class Application < Rails::Application ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| if html_tag.sub!(/class="/, ‘class=“field_with_errors ‘).nil? html_tag.sub! /(/?>)/, ‘ class=”field_with_errors”\1’
end
html_tag.html_safe
}
end
end
[/ruby]

app/assets/stylesheets/xxx.css
[css]
input.field_with_errors, select.field_with_errors {
padding: 1px;
background-color: #8FC7DE;
display: table;
}
[/css]

または、spanタグで
[ruby]
module xxxxxx
class Application < Rails::Application ActionView::Base.field_error_proc = Proc.new {|html_tag, instance| %(#{html_tag})} end end [/ruby]

 Share!