LoginSignup
3
4

More than 1 year has passed since last update.

【Rails6】deviseで独自カラムを追加して使用する方法 ①

Last updated at Posted at 2021-05-05

はじめに

Railsのログイン認証で、deviseを使用する機会が多いかと思いますが、独自のカラムを追加して使用する方法をご紹介します。

今回のテーマは、独自カラムの追加とログイン時に独自のカラムで行えるようにすることにします。

環境

MacOS : Big Sur
Ruby : 3.0.1
Rails : 6.1.3.1

① gem devise 追加

Gemfile に追記していきます。

Gemfile
gem 'devise'

bundle install コマンドの実行

bundle install

② devise インストール

deviseをインストールする rails g devise:install コマンドを実行

rails g devise:install
Running via Spring preloader in process 4466
      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 *

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

③ Userモデル 作成

Userモデルを追加する rails g devise user コマンドを実行

rails g devise user
Running via Spring preloader in process 4487
      invoke  active_record
      create    db/migrate/20210505〇〇〇〇〇〇_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のUserモデルが作成されるので、作成されるマイグレーションファイルを編集し独自カラムを追加します。

④ マイグレーションファイル 編集

/db/migrate/20210505〇〇〇〇〇〇_devise_create_users.rb ファイルを編集していきます。

※ 生成されたマイグレーションファイルで、一部コメントアウト # t.string されているので、必要に応じて # を外します。

20210505〇〇〇〇〇〇_devise_create_users.rb_編集前
# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_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


      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
end
20210505〇〇〇〇〇〇_devise_create_users.rb_編集後
# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,                  null: false, default: ""
      t.string :encrypted_password,     null: false, default: ""
      #今回追加
      t.string :user_code,              null: false, default: "" #ユーザコード (ログインにも使用)
      t.string :user_last_name,         null: false, default: "" #姓
      t.string :user_first_name,        null: false, default: "" #名
      t.string :user_status,            null: false, default: "enable" #ステータス

      ## 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 # メール認証をする場合

      ## Lockable
      t.integer  :failed_attempts, default: 0, null: false # ロック機能を利用する場合 
      t.string   :unlock_token # ロック解除をメール等で行う場合
      t.datetime :locked_at


      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

    #今回追加
    add_index :users, :user_code,            unique: true

  end
end

上記のように、コメントアウト・追加したいカラムを追加していきます。
※ 今回は、初めの段階で、予定している使用機能のコメントアウト・追加したいカラムを追記しています。
マイグレーションした後でも、機能・カラムの追加は行えます。

⑤ マイグレーション 実行

マイグレーションを行う rails db:migrate コマンドを実行

rails db:migrate
== 20210505〇〇〇〇〇〇 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0041s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0016s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0014s
-- add_index(:users, :confirmation_token, {:unique=>true})
   -> 0.0016s
-- add_index(:users, :unlock_token, {:unique=>true})
   -> 0.0012s
-- add_index(:users, :user_code, {:unique=>true})
   -> 0.0015s
== 20210505〇〇〇〇〇〇 DeviseCreateUsers: migrated (0.0134s) =======================

ここまで行うと、ログイン機能が使用できるようになりますが、
今回は、独自カラムを追加しているので、ビューやコントローラをカスタマイズする必要があります。

長くなりましたので、記事を分けてご紹介しようと思います。
次回は、ビューのカスタマイズを行っていきたいと思います。

▽次の記事はこちら▽
【Rails6】deviseで独自カラムを追加して使用する方法 ②

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