Resetting a password I am trying to reset a password when password_reset_token is received in the controller. But it's becoming a long if else ladder of many conditions. Can it be reduced in a better way?

def set_new_password
    if params[:password_reset_token].present?
      @user = User.find_by(password_reset_token: params[:password_reset_token])
      if @user.present?
        if params[:password] != params[:password_confirmation]
          render json: {errors: ["Your password confirmation doesn't match"]}, status: :unprocessable_entity
        elsif @user.password_reset_sent_at &lt; 2.hours.ago
          render json: {errors: ["Your password reset expired. Please require a new password reset from the app."]}, status: :unprocessable_entity
        elsif @user.update(user_params)
          @user.update(password_reset_token: nil, password_reset_sent_at: nil)
          render :json =&gt; {:success =&gt; true}
        end
      else
         render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
      end
    else
      render json: {errors: ["Password reset not found. Please request a new password reset!"]}, status: 404
    end
  end
Below is refactoring code you can use:

def set_new_password
  @user = User.find_by(password_reset_token: params[:password_reset_token]) if params[:password_reset_token].present?

  unless user
    render json: {
       errors: ["Password reset not found. Please request a new password reset!"]
    }, status: 404 and return
  end

  if params[:password] != params[:password_confirmation]
    render json: { errors: ["Your password confirmation doesn't match"] }, status: :unprocessable_entity

  elsif @user.password_reset_sent_at &lt; 2.hours.ago
    render json: {
      errors: ["Your password reset expired. Please require a new password reset from the app."]
    }, status: :unprocessable_entity

  else
    updated_params = user_params.merge(password_reset_token: nil, password_reset_sent_at: nil)

    @user.update(updated_params) ?
      render :json =&gt; {:success =&gt; true} :
      render :json =&gt; {:success =&gt; false}
  end
end


I also suggest to move validation password confirmation match with password to model using standard ActiveRecord validation: http://guides.rubyonrails.org/active_record_validations.html#confirmation