LoginSignup
8
8

More than 3 years have passed since last update.

[Rails]devise機能でログインIDをusernameにしたらエラーになった

Posted at

deviseでログインIDをusernameにしたらエラー

Railsで新規登録&ログイン実装をするのに便利な機能であるdeviseを使用するにあたって、ログインIDがデフォルトではEmailとなっているので、これをusernameにしたい。

ということで、こちらの記事を参考に変更していった。
Railsのログイン認証gemのDeviseのカスタマイズ方法

これで簡単にusernameをログインID に設定できたと思いきや、
新規登録の際にこんなエラーが。。
スクリーンショット 2019-09-02 18.13.52.png

全項目しっかり埋めてもEmail can’t be blankとなってしまう。

Validateはvalidates :username, presence: true, uniqueness: trueだけなので、Emailに関して特に変更した記憶はない。

※usernameのカラムを追加する前はEmailで異常なく新規登録できていた。

なんとか解決できたので、解決策を自分のメモとして残しておきます。

解決策

devise can’t be blankで検索をかけるとStrongParameterの設定に関しての情報がやたら出てくる。

しかし、その書き方は多種多様。
そして、どれを試しても結果変わらずであったり、別のエラーを引き起こしたりで、上手くいかないなぁと感じていたところで
こちらのStrongParameterを実装してみた。
Publifyでユーザー登録するとCan’t be blankエラーの対応参照

controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    added_attrs = [:user_name, :email, :password, :password_confirmation, :remember_me]
    devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
    devise_parameter_sanitizer.permit :account_update, keys: added_attrs
  end
end

これだとエラーを起こすことなく、無事登録できました。

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