7
6

More than 3 years have passed since last update.

既存のRailsアプリに後からdeviseを導入する方法

Last updated at Posted at 2021-02-11

はじめに

作成中のRailsアプリにdeviseを導入した時のことを記事にします。
初めての記事ですので、間違っている点などあればコメントを頂ければありがたいです。
以下参考とさせて頂いた記事になります。



バージョン

rails  : 6.1.1
ruby   : 2.6.6
devise : 4.7.3

手順は初期の段階から導入する場合とそんなに変わりません


  1. まずGemfileにgemを記載してインストールします
gem 'devise' #追加
bundle install



2. 続いて以下のコマンドを実行します

rails g devise:install

以下のように表示されれば成功です

Running via Spring preloader in process 23773
      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 *

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




表示された内容に沿って1つずつ設定を確認

  1. deviseによって提供されるメール認証機能で認証メールに記載する認証リンクのURLを設定します 表示の通りに
/config/environments/development.rb
Rails.application.configure do
.
.
  # maeler setting
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
.
.
end

追加します。


2. deviseでは登録完了後などにroot_pathへ飛ぶ設定になっているので

config/routes.rb で設定する必要がありますが、今回は既存のアプリケーションなのですでに設定されていることと思います。




3. deviseで生成されるメッセージをViewに追加します

既存アプリなのですでに別のflashメッセージが設定されているかもしれませんが、そこはうまいこと。。。




4. デフォルトで提供されるdeviseのviewは非常に簡素なものなので、カスタマイズが必要になると思います。
カスタマイズするために以下のコマンドを実行します

$ rails g devise:views

既存のアプリにすでに実装されている機能と作成されたviewファイルは役割がかぶるものがあると思いますので、置き換えるなど対応していきます。その作業自体は後回しで大丈夫です。


deviseでモデルを更新する

以下のコマンドを実行しマイグレーションファイルを作成します。
なお、新しいモデルなのか、

すでにあるモデルに追加するのかは、railsがいい感じに解釈してくれます。多分。

$ rails g devise User
      create    db/migrate/[timestamp]_add_devise_to_users.rb
      insert    app/models/user.rb
       route  devise_for :users

追加されたものを1つずつ確認していきます

routes.rb
  devise_for :users

の一文が追加されます。これによりサインアップや、ログインなど認証のためのルーティングが自動で作成されます。

次に

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

devise以降の記述で使用するdeviseのモジュールを指定しています

モジュールに関してはこちらの記事を御覧ください

そして作成されたマイグレーションファイルは以下になります

# frozen_string_literal: true

class AddDeviseToUsers < ActiveRecord::Migration[6.1]
  def self.up
    change_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      # Uncomment below if timestamps were not included in your original model.
      # t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end

  def self.down
    # By default, we don't want to make any assumption about how to roll back a migration when your
    # model already existed. Please edit below which fields you would like to remove in this migration.
    raise ActiveRecord::IrreversibleMigration
  end
end

このファイルを編集していきます。編集内容は

  1. 先程モデルファイルで指定した、使用するモジュールに関連する部分だけコメントアウトを解除する
  2. すでに存在しているUserモデルとかぶっている部分は逆にコメントアウトしていきます

です。


編集し終わったら以下のコマンドを実行します

rake db:migrate

導入自体はとりあえず完了です。

此処から先はひたすらこれまでに設定していたルートやメソッドなどを 置き換えていく作業に入ります

テストなども全て書き直さないとダメですね。。。めんどくさい。

それについてはまた別の記事にしたいと思います。
ありがとうございました。

7
6
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
7
6