I have an auth system from scratch, and when a user clicks on 'edit profile' it has to input the current password no matter the field he wants to edit.
def update
if params[:user][:password].present?
authenticated = @user.authenticate(params[:user][:current_password])
if authenticated && @user.update(user_params)
redirect_to root_url
flash[:notice] = "Your profile was successfully updated!"
else
@user.errors.add(:current_password, 'is invalid') unless authenticated
render :edit
end
elsif @user.update(user_params)
redirect_to root_url
flash[:notice] = "Your profile was successfully updated!"
else
render :edit
end
end
How can I call authenticate or use some context model validation only for the scenario when the user wants to change his password?
You may create a nested if-else in this action statement that will check for existence of
new_passwordandnew_password_confirmation(or whatever the new password and confirmation fields are called) in theparams[:user]object. If they are present - you may redirect to some king of page with request to enter existent password.Another way is to use ajax to show asynchronously the dialog box with the same request (like respond_with self-invoking javascript function that handles that). Then handle submit button in of the dialog in the other action of the controller.
Update (considering use of validators):
Considering validation you may write your own validator (for password) and condition to check when the new password field come with some data from the client.
I think it could look like this: