1
3

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.

【rails】devise認証をemailではなく、違う項目でログインする。

Last updated at Posted at 2021-01-30

##実行環境
devise (4.7.3, 4.7.2, 4.7.1)
ruby 2.3.0p0
rails 5.1.4

##deviseのデフォルトカラムは、

 t.string :email,              null: false, default: ""
 t.string :encrypted_password, null: false, default: ""

##だがしかし、今回は部屋番号で認証したいので、下記と設定した。

t.string :room_number,        null: false
t.string :encrypted_password, null: false, default: ""

##そのために、下記を実施する。

config/initializers/devise.rb

deviseの設定を変更するため、下記を変更する。※devise (4.7.3, 4.7.2, 4.7.1)
  49  config.authentication_keys = [:room_number]
  61  config.case_insensitive_keys = [:room_number]
  66  config.strip_whitespace_keys = [:room_number]          
app/models/user.rb
以下3つのメソッドをオーバーライド(上書き)して無効化。
  def email_required? #バリデーションにemailの検証が必要かどうかを検証するメソッド
    false
  end

  def email_changed?
    false
  end
  def will_save_change_to_email?
    false
  end
controller.rb
ストロングパラメーターの設定
before_action :configure_sign_in_params, only: [:new, :create]
def configure_sign_in_params
  devise_parameter_sanitizer.permit(:sign_in, keys: [:room_number])
end

これで
スクリーンショット 2021-01-30 10 38 35

完成!!

##参考記事
[Rails] devise の使い方(Validatable Recoverable Rememberable)
https://tech.mof-mof.co.jp/blog/devise-option-methods-integrate-vrr/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?