Activation mail rails
In Rails, an activation mail is a type of email that is sent to a user after their account has been created or updated, typically to confirm their email address or to activate their account.
Here's a step-by-step guide on how to implement activation mail in Rails:
Step 1: Generate a migration to add an activation token
Run the following command to generate a migration that adds an activation_token
column to the users
table:
rails generate migration AddActivationTokenToUsers activation_token:string
Step 2: Run the migration
Run the following command to apply the migration:
rails db:migrate
Step 3: Create an activation mailer
Create a new mailer class called UserMailer
:
rails generate mailer UserMailer
Step 4: Define the activation mailer
In the UserMailer
class, define a method called activation_email
that sends an email to the user with an activation link:
class UserMailer < ApplicationMailer
def activation_email(user)
@user = user
mail to: @user.email, subject: "Activate your account"
end
end
Step 5: Generate an activation link
In the User
model, add a method called activation_link
that generates an activation link:
class User < ApplicationRecord
def activation_link
Rails.application.routes.url_helpers.activation_url(self, host: Rails.application.config.action_mailer.default_url_options[:host])
end
end
Step 6: Send the activation mail
In the User
model, add a method called send_activation_email
that sends the activation mail:
class User < ApplicationRecord
def send_activation_email
UserMailer.activation_email(self).deliver_now
end
end
Step 7: Update the user's activation token
In the User
model, add a method called update_activation_token
that updates the user's activation token:
class User < ApplicationRecord
def update_activation_token
self.activation_token = SecureRandom.hex(16)
save!
end
end
Step 8: Use the activation mailer in the controller
In the UsersController
, add a method called create
that sends the activation mail after creating a new user:
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
redirect_to root_url, notice: "Account created successfully"
else
render :new
end
end
end
Step 9: Add a route for the activation link
In the routes.rb
file, add a route for the activation link:
Rails.application.routes.draw do
get '/activate/:id', to: 'users#activate', as: :activate_user
end
Step 10: Implement the activation link
In the UsersController
, add a method called activate
that activates the user's account:
class UsersController < ApplicationController
def activate
user = User.find(params[:id])
user.update!(activated: true)
redirect_to root_url, notice: "Account activated successfully"
end
end
That's it! With these steps, you should now have an activation mail system in place in your Rails application.