Skip to content

Creating the user model

Giorgi Mezurnishvili edited this page Dec 13, 2023 · 2 revisions

Passwordless expects you to provide your own user model. If your project doesn't yet have one, you need to add it yourself.

First run the model generator:

$ bin/rails generate model User email

Then connect the User model with Passwordless. It's a good idea to add some validation rules:

# app/models/user.rb

class User < ApplicationRecord
  validates :email,
            presence: true,
            uniqueness: { case_sensitive: false },
            format: { with: URI::MailTo::EMAIL_REGEXP } # <-- validates that the email is in correct format, and that it is unique  

  passwordless_with :email # <-- tells Passwordless which field stores the email address
end

Make sure to repeat the validations at database level:

# db/migrate/******_create_users.rb

class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :email, null: false # <-- make the `:email` attribute required

      t.index 'LOWER(email)', unique: true, name: 'index_users_on_lowercase_email' # <-- prevent duplicate emails

      t.timestamps
    end
  end
end

Finally run the migration:

$ bin/rails db:migrate

Naming convention

Naming the model and the email field is up to you. For example your user model may be called Visitor and the email field may be called :email_address. Passwordless will still work, as long as you point it to the correct field with passwordless_with.