deviseを使ったユーザー情報の変更をする場合パスワードが保存されない時のedit画面での設定


deviseを使ったユーザー登録情報の編集をする場合、edit→updateを行うときビュー画面のエラーメッセージがCurrent password can't be blankと表示され、編集画面が保存されない場合の解決方法。

ruby '2.6.5'
rails '6.0.0
devise 4.7.2

2つのdeviseをもつアカウントがあり、ユーザー登録情報を編集し、保存をしたい場合の設定の流れをまとめます。

①ルーティングの確認/rails routes でuserのregistrations/editのパスを確認します。

edit_user_registration GET    /users/edit(.:format)                                                          users/registrations#edit

edit_user_registration_path と確認が取れました。これをlink_toでパスを作成します。

②controllers/users/registrations_controller.rb ファイルです。

before_actionとconfigure_account_update_paramsの設定をします。今回は私のカラムを載せます。

before_action :configure_account_update_params, only: [:update]
def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update,  keys: [:nickname, :email, :password, :gender_id, :birth, :bloodtype_id, :emergencyperson, :emergencycall, :real_name, :real_name_kana, :phone_number])
  end
③次にビューです。

users/registrationsにedit.html.erbファイルを作成します。ほぼnew.html.erbをコピーしたものを使いますが、追加事項があります。私は2つのdeviseを使ってるのでディレクトリが違いますが1つのdeviseだとビューはdevise/registrationsにedit.html.erbを作成します。

form_withのパスも変更します。
参考サイト こちらです
結論から言うと、deviseのデフォルト設定なのですが、パスワード更新時は現在のパスワードを認証してupdateを行います。

<%= form_with model: @user, url: user_registration_path, method: :patch, class: 'registration-main', local: true do |f| %>
 <div class="field">
    <%= f.label :current_password %> 
    <%= f.password_field :current_password, autocomplete: "current-password" %>
  </div>

こちらを追加します。編集する場合は今までのパスワードを入れる項目が必要と言うわけです。

これを追加することによって無事に変更項目が保存されました。ですがパスワードを変更しない場合も必須なのでそこが?と言う感じです。
引き続き調べて学習していきます。