Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active December 3, 2021 21:41
Show Gist options
  • Save stevepolitodesign/497e08dc7b482bce240cc50092616c5e to your computer and use it in GitHub Desktop.
Save stevepolitodesign/497e08dc7b482bce240cc50092616c5e to your computer and use it in GitHub Desktop.
Require an individual parameter.

Require an individual parameter in Rails.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment