0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

deviseを導入しよう1

0
Posted at

deviseのかんたん導入手順

devise導入ステップ

1.Gemfileでインストール
2.deviseをインストール
3.ユーザーテーブルを作成

です!

deviseとは

ユーザー機能を実装したいときに、1から実装しようとするとセキュリティ面等で実装がかなり、難しくなります。

そこで簡単にユーザー機能を簡単に作ることができるのが「devise」というGemです。

1.Gemfileでインストール

Gemfileの1番下に

gem 'devise'

Gemfileをインストールします
ターミナルで

$ bundle install

を実行して下さい!

deviseをインストール

deviseをインストールします
ターミナルで下記コマンド入力

$ rails g devise:install

下記内容が表示されればインストール成功です

Running via Spring preloader in process 7494
      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は新規登録時にメール送るときの設定なので、ここでは割愛

2はroot to: "home#index"なので、つまりroutes.rbroot to: になにか定義してね。という意味です。(URLが/のときのルーティング)

3はdeviseはデフォルトでフラッシュメッセージを表示できるので、使うならapp/views/layouts/application.html.erb.にコード書いてねーという意味ですね。

別に書かなくても問題はないですが、書くならapplication.html.erbbodyタグ<%= yield %>の上が一般的です

layouts/application.html.erb
  <body>
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>
    <%= yield %>
  </body>

4はviewをカスタマイズするならrails g devise:viewsしてねという意味です

ここまでで、deviseを使う準備ができました

ユーザーテーブルを作成

deviseのを使うとユーザーのテーブル作成が、コマンド1つで行えます!
rails g devise モデル名でテーブルができます

ターミナルで下記実行

$ rails g devise User

作成されたマイグレーションファイルを確認してみましょう

db/migrate/(年月日時分秒)_devise_create_users.rb
# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  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

ユーザー機能に必要なテーブルが作成されました!
ただし、ここで注意する点が、、

それは、deviseのデフォルトのテーブルでは、名前を保存するカラムがありません。

なので、カラムを追加する必要があります。
マイグレーションファイルにt.string :name を追加しましょう

db/migrate/(年月日時分秒)_devise_create_users.rb
# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  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.string :name

      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

カラムが追加できたら、データベースへマイグレーションします

$ rails db:migrate

ここまでで、deviseのインストールからdeviseを使ったユーザーモデルの作成までできました

実際にログイン機能を作ってみよう

また次回、続きを載せますのでご期待下さい!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?