This article was originally published on . It will be a collection of pragmatic, practical articles with tips, insights and best practices on building a SaaS with Rails in 2024 and beyond.
Rails 8 ships (finally!) with authentication out-of-the-box. ❤️ When it launched most were surprised it didn't come with a way to register (sign up) a new user. But this was a conscious decision, because creating a User isn't typically the only resource needed for a SaaS. There are many other actions that need to be taken and resources created when someone new signs up for your product.
This article explores the way I do it using something, typically referred to as a Form Object. Let's check it out.
If you want to follow along, to improve your UI, CSS and JavaScript skills! 🧑🎓 🎨
Next up the route:
# config/routes.rb
root to: "pages#show"
resource :signups, path: "signup", only: %w[new create]
I also already added a root route, where the user will be redirected to upon successful sign up.
Then the controller. It is pretty straight-forward:
class SignupsController < ApplicationController
allow_unauthenticated_access only: %w[new create]
def new
@signup = Signup.new
end
def create
@signup = Signup.new(signup_params)
if user = @signup.save
start_new_session_for user
redirect_to root_url
else
redirect_to new_signups_path
end
end
private
def signup_params
params.expect(signup: [ :email_address, :password ])
end
end
allow_unauthenticated_access is coming from Rails' authentication generator. Then another little new thing is params.expect(signup: [ :email_address, :password, :terms ]). Previously you might have seen params.require(:signup).permit(:email_address, :password). It's a new Rails 8+ syntax, added in ! 💡
To finalize this from start to finish, let's create a simple view where the user is redirected to upon sign up.
# app/views/pages/show.html.erb
<p>Sign up Successful</p>
<%= button_to "Log out", session_path, method: :delete %>
Using this approach you have a class that can contain all required steps for sign ups. Easy to reason about, and easy to test!
Of course this is just the start! From UI and CSS (check out Rails Designer's UI Components Library) to adding validation messages and so on.
And with that you have added sign ups to your Rails 8 authentication. Also this code is not limited to Rails 8, and can be as easily added to older versions of Rails.
SOCIAL SHARE CARD GENERATOR