LoginSignup
5
4

More than 3 years have passed since last update.

Rails I18nの紹介 flashメッセージの日本語化

Last updated at Posted at 2020-05-06

I18nとは

Internationalizationの略。
国際化という意味です。このメソッドを使用し、railsのエラーメッセージや、
自分で設定したカラムの日本語化をすることができます。
今回は、フラッシュメッセージの日本語化に苦労したので、その方法を紹介します。
まずは、表示したい日本語の設定を行っていきます。

ja.yml
ja:
  notice:
    create: タスクを作成しました!
    update: タスクを編集しました!
    destroy: タスクを削除しました!

notice: noticeオプションはredirect_toメソッドで使用でき、フィードバックメッセージを渡すことができます。
先ほど設定した、「タスクを作成しました!」という文字を表示させるためには、t('notice.create')とコントローラーに記述します。

controller.rb
  def create
    @task = Task.new(task_params)
    if @task.save
    redirect_to tasks_path, notice: t('notice.create')
    else
      render :new
    end
  end
  def update
    if @task.update(task_params)
      redirect_to tasks_path, notice: t('notice.update')
    else
      render :edit
    end
  end

  def destroy
    @task.destroy
    redirect_to tasks_path, notice: t('notice.destroy')
  end

noticeをビューに記述すると、フラッシュメッセージを表示することができます。

index.html.erb
<p><%= notice %></p>

94466A9B-32D4-4E34-BE9E-0262683DE1E0_4_5005_c.jpeg

無事に日本語で表示することができました!

5
4
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
5
4