has_secure_password makes it easy to add secure password handling to your Rails models without writing complex code.
0
0
has_secure_password in Ruby on Rails
Introduction
When you want users to create accounts with passwords.
When you need to verify user passwords safely during login.
When you want to store passwords securely using encryption.
When you want to add password confirmation fields easily.
When you want to avoid handling raw passwords directly in your code.
Syntax
Ruby on Rails
class User < ApplicationRecord
has_secure_password
endYou must have a password_digest column in your database table.
This method adds password and password_confirmation attributes automatically.
Examples
Basic usage in a User model to enable password security.
Ruby on Rails
class User < ApplicationRecord
has_secure_password
endYou must add a
password_digest column to store encrypted passwords.Ruby on Rails
# In migration file class AddPasswordDigestToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :password_digest, :string end end
Set password and confirmation;
has_secure_password handles encryption and validation.Ruby on Rails
# Creating a new user with password user = User.new(username: 'alice', password: 'secret123', password_confirmation: 'secret123') user.save
Sample Program
This example shows how has_secure_password lets you create a user with a password, stores it securely, and then check the password later.
Ruby on Rails
class User < ApplicationRecord has_secure_password end # Simulate creating a user user = User.new(username: 'bob', password: 'mypassword', password_confirmation: 'mypassword') if user.save puts "User created with encrypted password: #{user.password_digest}" else puts "Failed to create user" end # Simulate authentication if user.authenticate('mypassword') puts "Password is correct!" else puts "Password is incorrect." end
OutputSuccess
Important Notes
Always use has_secure_password with a password_digest column.
Passwords are encrypted with bcrypt automatically.
Never store plain text passwords in your database.
Summary
has_secure_password adds easy and safe password handling to Rails models.
It requires a password_digest column and uses bcrypt encryption.
It provides password setting, confirmation, and authentication methods automatically.