When editing your account, you are required to provide your current password. However, you can't use the password
field in a form becuase that field is needed if you ever want to update the current password.
class User < ApplicationRecord
# This is a non-database-backed attribute needed in forms and controllers.
attr_accessor :current_password
end
class UsersController < ApplicationController
def update
# We can call this confidently because it is required.
if current_user.authenticate(params[:user][:current_password]) && current_user.update(update_user_params)
...
end
end
private
def update_user_params
params.require(:user).permit(:current_password, :password, :password_confirmation).tap do |update_user_params|
# This requires that the param is set, eliminating the need to call `params[:user][:current_password].present?`
update_user_params.require(:current_password)
end
end
end