LoginSignup
4
1

More than 1 year has passed since last update.

Rails 7.0.5、Bootstrap 5.2でDevise 4.9を動かす

Last updated at Posted at 2023-06-11

はじめに

前回の記事(Rails 7.0.5でBootstrap 5.2を動かす)の続きになります。RailsでBootstrap5が動く状態になってからのDeviseのインストールと設定について手順のメモになります。

環境
Rails 7.0.5
Ruby 3.1.2
Bootstrap 5.2.3
MySQL Ver 8.0.31 for macos13.0 on arm64 (Homebrew)
Mac OS Ventura 13.4

この記事が参考になってVPSにデプロイしたいと思った方はぜひ以下のリンクからVultr VPSを申し込んでみて下さい。

激安VPSのVultrで紹介者からのリンク経由でアカウント登録すると$100のクレジットをもらえるので、CentOS7, 8, MySQL 5.7, 8などの組み合わせをいろいろ試しました。このキャンペーンはいつ終わるか分からないので、興味のある方は以下のリンクからアカウント登録してください。あなたはクレジットをもらえるし、私にも多少のクレジットが入るらしいので、Win-Winです。

このリンクで$100もらえます

スクリーンショット 2023-06-11 午後12.24.36.png

私もリファラー経由でアカウントを作ったので$100もらえました。これで最初にあれやこれや試すのは無料でできます。
VultrCredit.png
関連記事

  1. Rails 7.0.5でBootstrap 5.2を動かす
  2. Rails 7.0.5、Bootstrap 5.2でDevise 4.9を動かす(今回の記事)
  3. Rails7.0+Devise4.9をBootstrap5でカッコよくする

1. Devise

Devise本体と多言語環境のi18n、高いセキュリティを提供するdevise-security、Bootstrap5のViewを生成するdevise-bootstrap5をまとめてインストールします。

(1) インストール

Gemfile
# Use Devise
gem "devise"
gem 'devise-security'
gem 'devise-i18n'
gem 'devise-i18n-views'
gem 'devise-bootstrap5'
rails_root
$ bundle install

Installing devise-bootstrap5 0.1.3
Installing orm_adapter 0.5.0
Installing responders 3.1.0
Installing warden 1.2.9
Installing bcrypt 3.1.18 with native extensions
Installing devise-i18n-views 0.3.7
Fetching devise 4.9.2
Installing devise 4.9.2
Fetching devise-i18n 1.11.0
Fetching devise-security 0.18.0
Installing devise-i18n 1.11.0
Installing devise-security 0.18.0
Bundle complete! 22 Gemfile dependencies, 90 gems now installed.
Bundled gems are installed into `./vendor/bundle`
Post-install message from devise:

[DEVISE] Please review the [changelog] and [upgrade guide] for more info on Hotwire / Turbo integration.

  [changelog] https://github.com/heartcombo/devise/blob/main/CHANGELOG.md
  [upgrade guide] https://github.com/heartcombo/devise/wiki/How-To:-Upgrade-to-Devise-4.9.0-%5BHotwire-Turbo-integration%5D

Devise 4.9.2が入りました。

(2) Deviseの構成

Rails 7ではHotwireやらTurboやらがDefaultとなったのでDeviseは4.9で対応しました。が、自分は使いたいだけなので、とにかく動くようにします。

Deviseの初期構成

Devise公式ページのやり方に沿って初期構成を実行します。

Devise:install実行

$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

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 *

===============================================================================

config/environments/development.rbに以下を追加。

config/environments/development.rb
  # Devise
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

app/views/layouts/application.html.erbに以下を追加。
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

現時点でのapplication.html.erb

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Device490</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>
  </head>

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

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

Deviseで使うユーザーのモデルを生成。

rails_root
$ rails generate devise user
      invoke  active_record
      create    db/migrate/20230611165330_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users

Deviseのオプションを全部使えるようにしたいのでapp/models/user.rbを編集。

app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :confirmable, :lockable, :timeoutable, :trackable, :omniauthable
end

omniauthableに必要なGemをインストール

Gemfile
gem 'omniauth'
rails_root
$ bundle install

Installing rack-protection 3.0.6
Installing hashie 5.0.0
Fetching omniauth 2.1.1
Installing omniauth 2.1.1
Bundle complete! 23 Gemfile dependencies, 93 gems now installed.
Bundled gems are installed into `./vendor/bundle`

DBにDeviseのテーブルを作成するためにマイグレーション実行。

rails_root
$ rails db:migrate
== 20230611165330 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0383s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0148s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0064s
== 20230611165330 DeviseCreateUsers: migrated (0.0597s) =======================

(3) DeviseのView作成

DeviseのViewはDeviseのコマンドで生成されるが、それだけだとカッコ悪いのでdevise-bootstrap5を使ってカッコ良くします。devise-bootstrap5はRails 6用と書いてありますがViewを作るだけなのでRails 7でも問題ありません。

日本語のDevise i18nファイルを生成します。これはrails generate devise:views:bootstrapより前に実行します。

$ rails g devise:i18n:locale ja
      create  config/locales/devise.views.ja.yml

公式ページの手順にしたがって以下のコマンドを実行してViewを作成します。i18nに対応した内容になってました。

rails_root
$ rails generate devise:views:bootstrap
      create  app/views/devise
      create  app/views/devise/confirmations/new.html.erb
      create  app/views/devise/passwords/edit.html.erb
      create  app/views/devise/passwords/new.html.erb
      create  app/views/devise/registrations/edit.html.erb
      create  app/views/devise/registrations/new.html.erb
      create  app/views/devise/sessions/new.html.erb
      create  app/views/devise/shared/_error_messages.html.erb
      create  app/views/devise/shared/_links.html.erb
      create  app/views/devise/unlocks/new.html.erb

(4) Deviseのメールの雛形作成

次にDeviseが送信するメールの雛形を生成します。

rails_root
$ rails generate devise:i18n:views -v mailer
      invoke  Devise::I18n::SharedViewsGenerator
       exist    app/views/devise/shared
    conflict    app/views/devise/shared/_error_messages.html.erb
  Overwrite /Users/nakagawa/RubymineProjects/device490/app/views/devise/shared/_error_messages.html.erb? (enter "h" for help) [Ynaqdhm] Y
       force    app/views/devise/shared/_error_messages.html.erb
    conflict    app/views/devise/shared/_links.html.erb
  Overwrite /Users/nakagawa/RubymineProjects/device490/app/views/devise/shared/_links.html.erb? (enter "h" for help) [Ynaqdhm] Y
       force    app/views/devise/shared/_links.html.erb
      invoke  Devise::I18n::MailerViewsGenerator
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/email_changed.html.erb
      create    app/views/devise/mailer/password_change.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb
      invoke  i18n:form_for
       exist    app/views/devise/mailer
   identical    app/views/devise/mailer/confirmation_instructions.html.erb
   identical    app/views/devise/mailer/email_changed.html.erb
   identical    app/views/devise/mailer/password_change.html.erb
   identical    app/views/devise/mailer/reset_password_instructions.html.erb
   identical    app/views/devise/mailer/unlock_instructions.html.erb

この時点ではi18nの翻訳ファイルは適用されてました。

スクリーンショット 2023-06-11 午後7.29.02.png

(5) i18n Default言語を設定

app/config/application.rbにDefault言語を設定します。

app/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 Device490
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0

    # Configuration for the application, engines, and railties goes here.
    #
    # These settings can be overridden in specific environments using the files
    # in config/environments, which are processed later.
    #
    # config.time_zone = "Central Time (US & Canada)"
    # config.eager_load_paths << Rails.root.join("extras")

    # i18n Default言語を設定します。
    config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
    config.i18n.default_locale = :ja

  end
end

もし、ブラウザからのリクエスト毎に言語を設定したい場合はbefore_actionを使って設定できます。

コントローラー内に記述
before_action do
  I18n.locale = :es # Or whatever logic you use to choose.
end

ここで気付いたのだけど言語ファイルに抜けているDeviseメッセージがあるようなので、devise-i18nの公式サイトから必要なファイルをダウンロードしてapp/config/locales/devise.xxxx.ymlを上書きしました。

2. Bootstrap5を使ってのカッコいいDeviseページの作成

上記までの手順で個々のDeviseのページはBootstrap5ベースで作成されていますが、これをBootstrap5的なカッコいい形で使いたいと思います。Bootstrap4まではRails_LayoutというGemである程度自動でNavbarからサインアップのボタンが出たり、サインインのドロップダウンが出たりしたのですが、更新が止まっているようでBootstrap5には対応していません。

長くなるのでDeviseをBootstrap5的なカッコいい形で使う手順は別記事で書きたいと思います。

参考記事

Devise公式ページ
Devise views with Bootstrap 5 and i18n support
devise-i18n公式ページ

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