Just do IT

思うは招く

Rails アプリに devise を導入し、日本語化する

やりたいこと

  • devise を入れてユーザー認証機能をつくりたい
  • ついでに日本語化もしたい

手順

適当な Rails アプリを作成。

$ rails new devise-test

gemfile に今回使うgemを追記し bundle install 。

gem "devise"
gem "devise-i18n"

deviseの機能をRailsアプリにインストール。

$ bin/rails g devise:install

こんな表示が出る。

Depending on your application's configuration some manual setup may be required:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

     In production, :host should be set to the actual host of your application.

     * Required for all applications. *

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"
     
     * Not required for API-only Applications *

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

     * Not required for API-only Applications *

  4. You can copy Devise views (for customization) to your app by running:

       rails g devise:views
       
     * Not required *

ひとまず上から順に対応していく。4は後で別コマンドでおこなうので無視する。

config/environments/development.rb

#適当な場所に追記
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

ルーティング

routes.rb

Rails.application.routes.draw do
  #追記(あとで作る)
  root to: "home#index"
end

viewの編集

フラッシュメッセージと、ログインしてたら「ログアウトする?」を表示させるための記述をする。

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>DeviseTest</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    #追記
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>

    <% if user_signed_in? %>
      <%= link_to 'ログアウト', destroy_user_session_path, method: :delete %>
    <% end %>
    #追記ここまで

    <%= yield %>
  </body>
</html>

Userモデル作成

ユーザーについての情報を保存するモデルをつくる。以下のコマンドで、deviseの機能をもったユーザーモデルが作られる。

$ bin/rails g devise User

マイグレーションを実行。

bin/rails db:migrate

devise認証用のviewファイルを生成

日本語化に対応したdeivseのviewファイルを生成する。

$ bin/rails g devise:i18n:views

画面表示のためのコントローラーを作成しておく。

$ bin/rails g controller home index

ログインしていなければ認証画面を表示させるため、before_action :authenticate_user!, only: :indexを追記。

app/controllers/home_controller.rb

class HomeController < ApplicationController
  #追記
  before_action :authenticate_user!, only: :index
  
  def index
  end
end

ログイン後にEmailアドレスを表示させるよう記述。

app/views/home/index.html.erb

<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>

#追記
<%= current_user.email %>

サーバーを起動。

$ bin/rails server

localhost:3000 へアクセス。

f:id:K_Koh:20200818113844j:plain

確認しても日本語にはなっていない。

ロケール変更

アプリのデフォルトロケールを変更。

config/application.rb

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module DeviseTest
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    #以下2文を追記
    config.i18n.default_locale = :ja
    config.time_zone = "Asia/Tokyo"

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end
  • config.i18n.default_locale = :jaを追記することで日本語になる
  • config.time_zone = "Asia/Tokyo"タイムゾーンの設定

サーバーを再起動させて確認してみると。

f:id:K_Koh:20200818113955j:plain

日本語化された。登録ページも日本語化されているので、「アカウント登録」を押して適当なメールアドレスで登録してみると・・・

f:id:K_Koh:20200818114122j:plain

Emailが表示された。ログインが成功し、メッセージも日本語になっている。

リポジトリ

https://github.com/kotakanazawa/devise-test

ロケールファイルは必要ないのか?

devise-i18nを使った場合、日本語の基本的な翻訳ファイルは gem に含まれている。なのでja.ymlに日本語のエラーメッセージなどを追記する必要はない。

カスタマイズや追加をしたくなったら、

$ bin/rails g devise:i18n:locale it

でファイルを生成できる。

参考