Build invitation in rails 7

Xin Jiang
3 min readMay 4, 2024

--

If you using rails to build business projects you must encountered a problem must solve: the invitation. You act as admin invite other users to join the company. I will show you how to do it in this article.

Let’s make it happen from scratch.

First you need a user model:

I use devise. This gem is already defactor for rails authentication. https://github.com/heartcombo/devise

And then, you need to create the invitation model.

The relationship is company has many users and user has many invitations. There are recipient_email and token in invitation model. Which we will cover later.

After all of those be settled, let’s move to the UI.

The logic is the admin input the email to invite other user join the company. This is the HTML:

Here I use turbo frame because I need it just update part of the UI, not all. The controller:

After the admin input the email and press the invite button, the invitation model will be created. And then we will issue a mailer to notice the user. The mailer is:

and the mailer view:

Notice, I added an invitation token in the registration url. The token is from here:

the “has_secure_token” will set the token. So the process is:

  1. admin input user’s email and press invite
  2. the invitation controller create an invitation model and set the unique token
  3. invitation mail be sent by controller, with the token setted
  4. user click the address in the email, go to the registration page:

We have a hidden field to make submit token possible:

After user submit the form:

I have a method in before action. Get the token, find the invitaion. and set company. When user created the right company linked to user.

There just one thing we need notice. Fallback. If User is not invited, he will be linked to a default company name.

--

--

Xin Jiang

Founder of 37yu, QUMGE CEO, Commerize CTO; We sharp the future with AI