🚪Login with Devise
Set Up Devise
Follow these steps to configure Devise for user authentication in your Lightning Rails application.
Configure Devise
Open the production.rb file at config/environments/production.rb
and customize the host domain to match your production domain.
# config/environments/production.rb
config.action_mailer.default_url_options = { host: 'example.com' } # Change this to your domain
Configure email address for Devise::Mailer
#config/initializers/devise.rb
config.mailer_sender = '[email protected]'
(Optional): Further Customization of Devise
To customize the User model by adding additional fields like first_name
and last_name
, follow these steps:
Generate a Migration
Generate a migration to add the new fields to your User model:
rails generate migration AddFieldsToUsers first_name:string last_name:string
Migrate the Database
Run the migration to update the database schema:
rails db:migrate
Permit Additional Parameters
To allow these new fields during sign-up and account update, you need to update the Devise parameters. Open or create the app/controllers/application_controller.rb
file and add the following code:
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name])
end
end
Update Views (Optional)
If you want users to input these additional fields during sign up and account editing, you must update the Devise views. Edit the app/views/devise/registrations/new.html.erb
and app/views/devise/registrations/edit.html.erb
files to include the new fields:
<div class="field">
<%= f.label :first_name %>
<%= f.text_field :first_name, autofocus: true %>
</div>
<div class="field">
<%= f.label :last_name %>
<%= f.text_field :last_name %>
</div>
This will allow users to provide their first and last names when they sign up or update their account information.
Freeing a Page from Authentication
To allow access to a specific action without requiring user authentication, you can use the following code in the corresponding controller:
class YourControllerName < ApplicationController
# Freeing the action from authentication
skip_before_action :authenticate_user!, only: :action_name
def action_name
# Your action code here
end
end
Make sure to change "action_name" to your new action name and "YourControllerName" to your new or existing controller name.
Additional Resources
For more information and advanced configurations, we invite you to check out the official Devise repository on GitHub:
Last updated
Was this helpful?