LoginSignup
22
26

More than 3 years have passed since last update.

Rails エラーメッセージの表示と日本語化

Posted at

エラーメッセージの表示

image.png

上記の画像のようにタイトルとブログ本文が空だった場合はエラー表示される様に実装する事。

モデルにバリデーションを設定

バリデーションを付けたいモデル(今回はpost.rb)に記載。

post.rb
class Post < ApplicationRecord
  validates :title, :content, presence: true
end

titleカラムとcontentカラムが空を防ぐ。

エラーメッセージのファイルの作成

エラーメッセージはエラーが発生すると、_error_messages.html.erb内に格納される。

layouts/_error_messages.html.erb
% if model.errors.any? %>
  <div class="alert alert-warning">
    <ul>
      <% model.errors.full_messages.each do |message| %>
        <li><%= message %></li> 
      <% end %>
    </ul>
  </div>
<% end %>

フォーム(form_with)の中にrenderで挿入

posts/new.html.erb
<%= form_with model: @post, class: :form, local: true do |form| %>
 #renderメソッドで_error_messages.html.erbを呼び出す。
  <%= render 'layouts/error_messages', model: form.object %> 
  <%= form.text_field :title, placeholder: :タイトル, class: :form__title %>
  <%= form.text_area :content, placeholder: :ブログ本文, class: :form__text %>
  <%= form.submit '投稿する', class: :form__btn %>
<% end %>

これで表示は完了。
次は日本語化実装へ。

エラーメッセージの日本語化

Gemfile
gem 'rails-i18n'

Gemfileに以下の一文を追加して、bundle install。

日本語化の基となるファイルを作成する

Railsの多言語化対応は、ymlファイルで管理。
config/locales ディレクトリ直下に、ja.ymlを作成。

ターミナル
$ touch config/locales/ja.yml

カラム名の日本語化

config/locales/models/ja.yml
ja:
  activerecord:
    attributes:
      post:
        title: 名前
        content: ブログ本文

ja.ymlの注意点

Railsはymlファイルの改行とインデントで日本語化のパスを参照している為、
attributes: => モデル名 => カラム名 の順に改行とインデントを入れる必要がある。

config/locales/models/ja.yml
attributes:         # attributes:の直下に
  post:            # モデル名を指定し
    title: 名前        # カラム名を指定する。
   content:ブログ本文    # カラム名を指定する。

22
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
26