Adding Sign Up to the Rails 8 Authentication Generator
This article spurned from writing about the new Rails 8 Authentication Generator in my Build A SaaS App in Ruby on Rails 8 book, and I wanted to share this small tip from the chapter on Users and Authentication.
Within the book, I set up a Rails 8 application with authentication using the bin/rails generate authentication
command. This command creates a User model, a Sessions controller, and a few views to get you started. However, it does not include a Sign-up process at all.
In this quick article, we will add a Sign-Up form to the application.
Prerequisites
Before we start, ensure you have the Rails 8 application set up with the authentication generator.
Adding Sign Up
To add a Sign-Up form, we will need to add a few things:
- A route to the Sign Up form
- A controller action to render the Sign-Up form
- A view to display the Sign Up form
- A controller action to handle the form submission
Route
In the config/routes.rb
file, add a route to the Sign Up form in addition to the routes created by the authentication generator:
Controller
Create a new controller called RegistrationsController
:
It’s pretty standard stuff here. First, allow_unauthenticated_access
is a method that allows unauthenticated access to the new
and create
actions. Otherwise, we could use this controller with a valid session. The only other thing that is not standard Rails controller CRUD is the start_new_session_for @user
, which allows the app to be signed in (add session record, secure cookie, etc.) after the user is created.
View
Create a new view file called new.html.erb
in the app/views/registrations
directory (view assumes Tailwind was added and has some classes):
Form Submission
If you were to try to submit the form now, it would work, but redirect to the registration form as there is no root path or authenticated path to test this all out on. Let’s create a quick controller and route to handle this:
If you visit the root path of your application, you should see the Sign-Up form. You can fill it out and submit it to create a new user. Upon successful creation, you should be redirected to the root path with the message “Welcome to the app!”
Bonus Idea
Usually, when building an app, there is a different layout when you are logged in than when you are on one of the “authentication adjacent” pages. You can add a method to the ApplicationController
to determine if the user is authenticated or not:
Then, in your app/views/layouts
directory, create two layout files: application.html.erb
and authentication.html.erb
. In the application.html.erb
file, you can add a navigation bar, footer, etc. You can add a different navigation bar, footer, etc., in the authentication.html.erb
file.