ActiveModelをインクルードしたクラスでvalidationでエラーにする場合、項目の名前をconfig/locales/**.ymlに設定してあげないとキーの値がそのまま出てしまう(正確にはアンダースコアがスペースに置換される)
例えばこんな感じで検索用のモデルを作成して
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
module Tasks class Search include ActiveModel::Model attr_accessor :created_at_from, :created_at_to validate :created_at def created_at errors.add(:created_at_from, 'が不正です!') if created_at_from.blank? errors.add(:created_at_to, 'が不正です!!') if created_at_to.blank? end end end |
Viewではこんな感じで書く
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<h1>Home#index</h1> <p>Find me in app/views/home/index.html.erb</p> <div> <% @search.errors.full_messages.each do |msg| %> <p><%= msg %></p> <% end %> <%= form_for @search, url: root_path, method: :get do |f| %> <%= f.text_field :created_at_from, class: 'datepicker' %> <%= f.text_field :created_at_to, class: 'datepicker' %> <%= f.submit '送信' %> <% end %> </div> |
すると、validationエラーはキー値がそのまま表示される(コントローラ側で@search.valid?を呼び出してvalidationを走らせる)
これはi18nの設定をすれば、キー値を日本語化することが可能。
まずは、config/environments/***.rbでdefault_localeを設定する
1 2 3 4 |
Rails.application.configure do ... config.i18n.default_locale = :ja end |
config/locales/ja.ymlには以下のように設定すればOK
1 2 3 4 5 6 7 8 |
ja: activemodel: models: tasks/search: "検索フォーム" attributes: tasks/search: created_at_from: 開始日 created_at_to: 終了日 |
するとこんな感じで表示されるようになる
参考URL
- Rails4 DB連携なしモデルでバリデーション機能を使う – Qiita
- Railsのモデルのバリデーションエラー errors や full_messages の使い方 – Rails Webook
- ActiveMode::Modelのi18nの書き方 – 私の歴史と今
- ActiveModel::Model をインクルードしたモデルのアトリビュートの i18n – わからん
- Railsの多言語化対応 i18nのやり方を整理してみた!【国際化/英語化】 – 酒と泪とRubyとRailsと
コメントを残す