Devise.1 設定
以前、Devise gemを使って簡単なログイン機能をつくったが、その後かなり時間があいてしまったため、つくった過程や、そもそも何をつくった忘れてしまった(笑&汗)
そこで、実行画面とコードを参考に、そのつくり方を思いだしたい。
1.2 サイトの補足
1.2.1 「5.omniauth-twitter用カラムの追加」
Twitter認証はあとからでもいいかと考え、このセクションは飛ばした。
ただ、usernameはUserテーブルに追加しとくとよい。
$ rails g migration add_columns_to_users username:string
最初にDeviseを設定したとき、usernameをUserテーブルに追加しなかったため、エラーが出て焦ってしまった(笑)
class AddColumnsToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :username, :string end end
username
が備わった!後の「Twitterで認証する」というチャプターも飛ばした。
1.2.2 コントローラ
コントローラとしては、Pagesコントローラで、indexアクションとshowアクションをもつものだけを生成している
$ rails g controller Pages index show
index
がトップページ、show
がログインしているユーザー用のページになる予定とのこと
<h1>ようこそ</h1> <p>トップページです。</p>
<h1>こんにちは、<%= current_user.username %>さん</h1> <p>ユーザー用ページです。</p>
1.2.3 View
rails g devise:views
でDeviseのviewを生成
1.2.4 Userモデル
$ rails g devise User
マイグレーションは次のとおり
# 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
1.3 参考サイト
usernameカラムの追加には次も参考になる
qiita.com