Create Task Manager app: Implement – Rails API, JWT Authentication

In this session let’s get into our applications Authentication section where we decided to move on with JWT token. Here I state that the decision of moving with JWT token is solely for my experience purpose where I already have implemented the token based applications.

The best fit for our application’s authentication system is the Opaque token based authentication. But when we create big applications which has many services connected together and need to be compatible with different platforms/hardwares, jwt is the key for the centralized authentication system.

Step 4.1 – Rails API structure and first endpoint

Before building Task CRUD endpoints, let’s establish our API structure and see how Rails handles HTTP requests.

One important decision: We’ll implement JWT authentication before exposing task data. I don’t want to build an endpoint that returns every user’s tasks and later re-fit authorization.

Understand our API structure

We’ll use versioned API namespaces.

backend/
├── app/
│   ├── controllers/
│   │   ├── application_controller.rb
│   │   └── api/
│   │       └── v1/
│   │           └── authentication_controller.rb
│   │
│   ├── models/
│   │   ├── user.rb
│   │   └── task.rb
│   │
│   └── ...
│
├── config/
│   └── routes.rb
│
└── spec/
    ├── models/
    └── requests/
        └── api/
            └── v1/

Why version the API?

Suppose we eventually release our API to external consumers. We might introduce breaking changes in the future.

/api/v1/tasks
/api/v2/tasks

We can maintain both versions during a migration rather than breaking existing clients.

Understand JWT architecture

JWT stands for JSON Web Token. It is a compact format for securely transmitting claims between parties.

A JWT consists of three parts:

Header example

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload example

{
  "sub": "42",
  "iss": "task_manager_api",
  "aud": "task_manager_web",
  "iat": 1795000000,
  "exp": 1795000600,
  "jti": "unique-token-id"
}

Signature: Generated using the encoded header, encoded payload and signing secret. It allows Rails to detect token modification.

The complete token looks like: xxxxx.yyyyy.zzzzz

Each part is Base64URL encoded, and the signature is cryptographically generated.

Important: JWT is not encrypted by default. Anyone who obtains a JWT can decode its header and payload. The signature protects integrity, not confidentiality. Never put passwords or sensitive personal information in the payload.

Understand the claims we will use

Claims are the information carried inside the JWT payload.

ClaimMeaningOur usage
subSubjectUser ID
issIssuerOur Rails API
audAudienceOur React application
iatIssued atToken creation time
expExpirationToken expiry
jtiJWT IDUnique token identifier

Two important concepts:

sub – Subject – Identifies the user associated with the token.

We’ll use: {
"sub": "42"
}

When Rails receives the token, it can identify user ID 42 after verifying the signature.

exp – Expiration – Defines when the access token expires.

Our initial policy:

10 min – Access token lifetime – Short-lived JWT

7 days – Refresh session lifetime – Initial policy, configurable

We’ll implement refresh-token expiration and rotation separately.

Which signing algorithm should we use?

We’ll start with HS256.

AlgorithmDescription
HS256HMAC using SHA-256 and a shared secret
RS256RSA with SHA-256, using private/public keys
ES256ECDSA with SHA-256

Why HS256?

Our architecture currently has one Rails application that both generates and verifies tokens.

  • Rails has the signing secret.
  • Rails verifies signatures using the same secret.
  • We don’t need public/private key infrastructure yet.

One security rule: the verification algorithm must be explicitly allowlisted. Never trust the alg value supplied in an unverified token header to choose the verification algorithm.

Q) Why use JWT? How we trust the JWT payload/header? JWT vs Opaque token

Read detail here(Premium Content): https://railsdrop.com/why-use-jwt-how-we-trust-the-jwt-payload-header/

Install Ruby JWT gem

We’ll use the official Ruby implementation: https://github.com/jwt/ruby-jwt

From your backend directory: cd backend

Add to your Gemfile:

gem "jwt"

Keep it outside the development/test group because we’ll need it in production too.

Install: bundle install

Verify: bundle info jwt

The gem provides:

JWT.encode(payload, secret, algorithm)
JWT.decode(token, secret, true, algorithm: algorithm)

We’ll use these methods shortly.

Configure the JWT signing secret

This is an important security decision. Never hardcode the JWT secret inside your service class.

Generate a secure secret:

bin/rails secret

Copy the generated value temporarily.

Now edit Rails credentials:

VISUAL="code --wait" bin/rails credentials:edit

Add:

jwt:
  secret_key: YOUR_GENERATED_SECRET

Save and close the editor.

Rails stores credentials encrypted in: config/credentials.yml.enc. The encryption key is stored separately in: config/master.key

The encrypted credentials file can be committed to Git. Never commit master.key. Also, never paste your actual signing secret into our conversation. Later, we’ll configure separate production secrets through deployment/CI environment configuration.

Our authentication service structure

Let’s establish the structure before implementing the login flow.

app/
├── controllers/
│   └── api/
│       └── v1/
│           └── authentication_controller.rb
│
├── services/
│   └── authentication/
│       ├── access_token.rb
│       ├── token_verifier.rb
│       └── refresh_token.rb
│
└── models/
    ├── user.rb
    └── refresh_session.rb

Each component has a separate responsibility.

ComponentResponsibility
AccessTokenGenerate signed JWT
TokenVerifierDecode and verify JWT
AuthenticationControllerLogin, logout and refresh HTTP endpoints
RefreshTokenServiceGenerate, rotate and revoke refresh tokens
RefreshSessionPersist refresh-token session information

We’ll build these individually.

HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key and a hash function (such as SHA-256) to verify both the integrity and authenticity of a message.

HS256 (HMAC using SHA-256) is a symmetric cryptographic algorithm used to sign and verify JSON Web Tokens (JWT).

Modified implementation

I want to create a AccessToken class which is clean and not having any constants, error handling code etc. Let’s add a Base class and move the constants and the data which are rarely changes. Also create an Error module in which we store the error related data and will be available across all the classes via mixin.

A. authentication/error.rb

Convert Error into a module.

# frozen_string_literal: true

module Authentication
  module Error
    USER_ERROR = "A persisted user is required"
    SECRET_MISSING = "JWT signing secret is missing"

    def secret_length(length)
      "JWT signing secret must be at least #{length} bytes"
    end
  end
end

Why a module?

We want to reuse error messages and the secret_length helper across authentication classes.

We’ll use extend Error in Base, rather than include Error, because our helper needs to be available in class-method context.

B. authentication/base.rb

Move the common payload generation and secret management here.

# frozen_string_literal: true

require "securerandom"

module Authentication
  class Base
    extend Error

    ALGORITHM = "HS256"
    ISSUER = "task_manager_api"
    AUDIENCE = "task_manager_web"
    ACCESS_TOKEN_TTL = 10.minutes
    SECRET_BYTE_SIZE = 32

    class << self
      def payload
        now = Time.current.to_i

        {
          iss: ISSUER,
          aud: AUDIENCE,
          iat: now,
          exp: now + ACCESS_TOKEN_TTL.to_i,
          jti: SecureRandom.uuid
        }
      end

      private

      def signing_secret
        secret = Rails.application.credentials.dig(:jwt, :secret_key)

        raise KeyError, Error::SECRET_MISSING if secret.blank?

        if secret.bytesize < SECRET_BYTE_SIZE
          raise KeyError, secret_length(SECRET_BYTE_SIZE)
        end

        secret
      end
    end
  end
end

Notice two important things:

  1. payload is now a class method. Subclasses inherit it.
  2. signing_secret is a private class method. Subclasses can use it internally without exposing it as a public API.

C. authentication/access_token.rb

Your AccessToken class becomes much cleaner.

module Authentication
  class AccessToken < Base
    class << self
      def issue(user)
        unless user&.persisted?
          raise ArgumentError, Error::USER_ERROR
        end

        token_payload = payload.merge(sub: user.id.to_s)

        JWT.encode(token_payload, signing_secret, Base::ALGORITHM)
      end
    end
  end
end

This achieves what I wanted:

  • Constants stay in Base.
  • Errors stay in Error.
  • Common payload generation stays in Base.
  • AccessToken only handles access-token generation.

Also, sub is now a string, as required for the JWT Subject claim.

Q) Error: NameError:
uninitialized constant #<Class:Authentication::AccessToken>::ALGORITHM
# ./app/services/authentication/access_token.rb:11

When I modified the line:

JWT.encode(token_payload, signing_secret, ALGORITHM) TO
JWT.encode(token_payload, signing_secret, Base::ALGORITHM) it works. Why?

Find the answer here(Premium): https://railsdrop.com/ruby-constant-lookup-inside-a-singleton-class-class-self/

Modified RSpec specifications

I’d keep two spec files. We should test the shared Base functionality separately and test the actual JWT through its public issue method.

A. spec/services/authentication/base_spec.rb

require "rails_helper"

RSpec.describe Authentication::Base do
  describe ".payload" do
    let(:payload) { described_class.payload }

    it "includes the common JWT claims" do
      expect(payload.keys).to include(
        :iss, :aud, :iat, :exp, :jti
      )

      expect(payload).not_to have_key(:sub)
    end

    it "sets the correct issuer and audience" do
      expect(payload[:iss]).to eq("task_manager_api")
      expect(payload[:aud]).to eq("task_manager_web")
    end

    it "sets the expiration relative to issued time" do
      expect(payload[:exp] - payload[:iat]).to eq(10.minutes.to_i)
    end

    it "generates a unique JWT ID" do
      first_payload = described_class.payload
      second_payload = described_class.payload

      expect(first_payload[:jti]).not_to eq(second_payload[:jti])
    end
  end
end

Note: we’re testing the common functionality, not private implementation details.

B. spec/services/authentication/access_token_spec.rb

require "rails_helper"

RSpec.describe Authentication::AccessToken do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }

  describe ".issue" do
    context "with a persisted user" do
      let(:token) { described_class.issue(user) }

      it "generates a JWT string" do
        expect(token).to be_a(String)
        expect(token.split(".").size).to eq(3)
      end

      it "contains the correct JWT header" do
        _payload, header = JWT.decode(
          token,
          secret,
          true,
          algorithm: described_class::ALGORITHM
        )

        expect(header["alg"]).to eq("HS256")
      end

      it "contains the correct claims" do
        payload, = JWT.decode(
          token,
          secret,
          true,
          {
            algorithm: described_class::ALGORITHM,
            iss: described_class::ISSUER,
            verify_iss: true,
            aud: described_class::AUDIENCE,
            verify_aud: true,
            required_claims: %w[sub iss aud iat exp jti]
          }
        )

        expect(payload["sub"]).to eq(user.id.to_s)
        expect(payload["iss"]).to eq("task_manager_api")
        expect(payload["aud"]).to eq("task_manager_web")
        expect(payload["iat"]).to be_a(Integer)
        expect(payload["exp"] - payload["iat"]).to eq(10.minutes.to_i)
        expect(payload["jti"]).to be_present
      end

      it "generates a different jti for every token" do
        first_token = described_class.issue(user)
        second_token = described_class.issue(user)

        first_payload = JWT.decode(first_token, secret, true, algorithm: "HS256").first
        second_payload = JWT.decode(second_token, secret, true, algorithm: "HS256").first

        expect(first_payload["jti"]).not_to eq(second_payload["jti"])
      end
    end

    context "without a persisted user" do
      it "raises an error when user is nil" do
        expect {
          described_class.issue(nil)
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end

      it "raises an error when user is not persisted" do
        expect {
          described_class.issue(build(:user))
        }.to raise_error(ArgumentError, Authentication::Error::USER_ERROR)
      end
    end
  end
end

The JWT.decode calls explicitly configure HS256 and validate the issuer, audience and required claims. This follows the Ruby JWT library’s verification API.

Why did we remove the Base payload test from AccessToken?

Your original test was:

payload = described_class.send(:payload, user)

There are two problems:

  • payload was an instance method.
  • send bypasses Ruby’s private-method visibility.

We don’t need that approach anymore.

Instead, our AccessToken spec tests the actual generated JWT and inspects its verified payload.

This is a stronger test of the service’s public behaviour.

Final directory structure

app/services/authentication/
├── base.rb
├── error.rb
└── access_token.rb

spec/services/authentication/
├── base_spec.rb
└── access_token_spec.rb

And as I decided, our future refresh-token implementation will be: app/services/authentication/refresh_token.rb

Run the tests

bundle exec rspec spec/services/authentication/

One security note: these tests verify JWT issuance. We haven’t yet implemented incoming token verification, which is where signature trust, expiry, issuer, audience and algorithm allowlisting must all be enforced.

My recommendation: Keep this structure. It is small, maintainable and leaves room for future authentication functionality without turning AccessToken into a large service class.

Next we’ll build Authentication::TokenVerifier using this same architecture.

JWT decoding and verification

1. What exactly are we verifying?

Remember our generated token: header.payload.signature

When Rails receives this token, it must verify:

CheckWhat are we protecting against?
SignatureToken modification or forged token
AlgorithmAlgorithm substitution attacks
Expiration (exp)Use of expired tokens
Issuer (iss)Tokens from an untrusted issuer
Audience (aud)Tokens intended for another application
Issued at (iat)Invalid or future issuance timestamps
Required claimsMissing identity or security information

The Ruby JWT library supports these checks directly through JWT.decode. We must explicitly specify the accepted algorithm.

2. Understand JWT.decode

We’ve already used this in our specs: JWT.decode(token, secret, true, options)

Let’s understand the arguments:

ArgumentMeaning
tokenIncoming JWT string
secretSigning secret
trueEnable signature verification
optionsAlgorithm and claim verification configuration

The return value is: [
decoded_payload,
decoded_header
]

For example: payload, header = JWT.decode(...)

Important: Never do this in production: JWT.decode(token, secret, false)

That disables signature verification. Decoding a token is not the same as trusting it.

3. Create TokenVerifier

Create:

touch app/services/authentication/token_verifier.rb
touch spec/services/authentication/token_verifier_spec.rb

Our intended structure:

app/services/authentication/
├── base.rb
├── error.rb
├── access_token.rb
├── token_verifier.rb
└── refresh_token.rb

We’ll follow your existing design:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        # Your implementation
      end
    end
  end
end

Decide what verify should return

I recommend this contract:

InputResult
Valid JWTVerified payload Hash
Expired JWTnil
Invalid signaturenil
Invalid issuernil
Invalid audiencenil
Malformed JWTnil
Missing tokennil

Why return the payload instead of the User object? Because these are separate responsibilities:

  • TokenVerifier verifies cryptographic authenticity and claims.
  • The authentication layer identifies the corresponding User.
  • The authorization layer decides whether that user can access a resource.

This separation will become useful when we implement current_user

Our implementation requirements

Implement Authentication::TokenVerifier.verify(token).

A. Validate the input – Reject missing or blank tokens.

B. Decode and verify the token – Use JWT.decode with:

  • Signature verification enabled.
  • Base::ALGORITHM as the fixed algorithm.
  • Base::ISSUER as the expected issuer.
  • Base::AUDIENCE as the expected audience.
  • Expiration verification enabled.
  • Issued-at verification enabled.
  • Required claims: sub, iss, aud, iat, exp, jti.

Your decoding options should conceptually look like:

{
  algorithm: Base::ALGORITHM,
  iss: Base::ISSUER,
  verify_iss: true,
  aud: Base::AUDIENCE,
  verify_aud: true,
  verify_expiration: true,
  verify_iat: true,
  required_claims: %w[sub iss aud iat exp jti]
}

See the https://github.com/jwt/ruby-jwt for the current option names and behaviour.

C. Return the verified payload

JWT.decode returns an array. We only need the first element. Return the payload after successfully validating the token. Also ensure the sub claim is a non-empty string.

D. Handle JWT errors

An invalid token should not crash our Rails application. For the current ruby-jwt 3.3 error hierarchy, use:

rescue JWT::TokenError
  nil

Version note: JWT::TokenError was introduced in 3.3.0. Older versions can use JWT::DecodeError, which remains a compatible superclass for decoding errors. You can check your installed version using: bundle info jwt

Do not rescue every StandardError. A missing signing secret or an application programming error should not silently become an invalid-token response.

RSpec assignment

Create these examples in: spec/services/authentication/token_verifier_spec.rb

Use:

RSpec.describe Authentication::TokenVerifier do
  describe ".verify" do
    # Your examples
  end
end

Implement these seven scenarios.

TestExpected result
Valid JWT generated by AccessTokenReturns Hash
Correct subjectsub matches User ID
Expired tokenReturns nil
Wrong signing secretReturns nil
Wrong issuerReturns nil
Wrong audienceReturns nil
Malformed token / nil tokenReturns nil

Useful testing hints

For the valid token:

user = create(:user)
token = Authentication::AccessToken.issue(user)

For creating an expired token in your spec, use the same signing secret but give it an expiration timestamp in the past.

For testing an invalid signature, generate a token using a different secret.

For issuer and audience tests, generate tokens with incorrect claims, but sign them using the legitimate application secret. This ensures we’re testing claim validation rather than signature failure.

We don’t need to use mocks or stubs yet. These tests should use real JWT generation and verification.

6. How our authentication flow will eventually work

Notice that successful JWT verification alone doesn’t prove that the user still exists or that their account is active. We’ll implement those checks in the next authentication milestone. Also, we’ll later introduce rate_limit and authorization checks in the relevant controllers.

TokenVerifier implementation

backend/app/services/authentication/token_verifier.rb:

module Authentication
  class TokenVerifier < Base
    class << self
      def verify(token)
        return nil unless token.is_a?(String) && token.present?

        options = {
          algorithm: Base::ALGORITHM,
          iss: Base::ISSUER,
          verify_iss: true,
          aud: Base::AUDIENCE,
          verify_aud: true,
          verify_expiration: true,
          verify_iat: true,
          verify_jti: true,
          required_claims: %w[sub iss aud iat exp jti]
        }

        payload, = JWT.decode(token, signing_secret, true, options)

        return nil unless valid?(payload["sub"])
        return nil unless valid?(payload["jti"])

        payload
      rescue JWT::TokenError
        nil
      end

      private

      def valid?(item)
        item.is_a?(String) && item.present?
      end
    end
  end
end

Why these changes?

CodeResponsibility
token.is_a?(String)Reject unexpected input types
signing_secretReuse secret validation from Base
algorithmOnly accept HS256
verify_issValidate trusted issuer
verify_audValidate intended audience
verify_expirationReject expired tokens
verify_iatReject invalid/future issuance times
verify_jtiVerify JWT ID
required_claimsReject missing claims
valid_subject?Ensure a valid user identifier
valid_jti?Ensure a non-empty token identifier
rescue JWT::TokenErrorConvert invalid JWTs into nil

One important distinction: We only rescue JWT token errors. If our signing secret is missing or misconfigured, the application should raise a configuration error rather than pretending the incoming token is invalid.

Complete RSpec specifications

backend/spec/services/authentication/token_verifier_spec.rb:

require "rails_helper"

RSpec.describe Authentication::TokenVerifier do
  let(:user) { create(:user) }
  let(:secret) { Rails.application.credentials.dig(:jwt, :secret_key) }
  let(:valid_token) { Authentication::AccessToken.issue(user) }

  let(:decoded_payload) do
    JWT.decode(
      valid_token,
      secret,
      true,
      algorithm: Authentication::Base::ALGORITHM
    ).first
  end

  describe ".verify" do
    context "with a valid token" do
      it "returns the verified payload" do
        result = described_class.verify(valid_token)

        expect(result).to be_a(Hash)
        expect(result["sub"]).to eq(user.id.to_s)
        expect(result["iss"]).to eq(Authentication::Base::ISSUER)
        expect(result["aud"]).to eq(Authentication::Base::AUDIENCE)
      end

      it "returns the jti claim" do
        result = described_class.verify(valid_token)

        expect(result["jti"]).to be_present
      end
    end

    context "with an invalid token" do
      it "returns nil for blank tokens" do
        expect(described_class.verify(nil)).to be_nil
        expect(described_class.verify("")).to be_nil
        expect(described_class.verify("  ")).to be_nil
      end

      it "returns nil for non-string input" do
        expect(described_class.verify(123)).to be_nil
      end

      it "returns nil for malformed tokens" do
        expect(described_class.verify("invalid-token")).to be_nil
      end

      it "returns nil for expired tokens" do
        expired_payload = decoded_payload.merge(
          "exp" => 1.minute.ago.to_i
        )

        token = JWT.encode(
          expired_payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an invalid signature" do
        token = JWT.encode(
          decoded_payload,
          SecureRandom.hex(32),
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect issuer" do
        payload = decoded_payload.merge(
          "iss" => "untrusted_api"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil for an incorrect audience" do
        payload = decoded_payload.merge(
          "aud" => "another_application"
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when a required claim is missing" do
        payload = decoded_payload.except("sub")

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end

      it "returns nil when issued at is in the future" do
        payload = decoded_payload.merge(
          "iat" => 5.minutes.from_now.to_i
        )

        token = JWT.encode(
          payload,
          secret,
          Authentication::Base::ALGORITHM
        )

        expect(described_class.verify(token)).to be_nil
      end
    end
  end
end

We’ll test real token generation and verification rather than mocking JWT.

Run the specifications:

bundle exec rspec spec/services/authentication/token_verifier_spec.rb

Then run both JWT service specs:

bundle exec rspec spec/services/authentication/

Understand an important distinction before our next step

Our verifier returns:

{
  "sub" => "42",
  "iss" => "task_manager_api",
  "aud" => "task_manager_web",
  "iat" => 1795000000,
  "exp" => 1795000600,
  "jti" => "..."
}

It does not return a User object.

The next authentication layer will do: User.find_by(id: payload["sub"])

Why query the database if JWT is self-contained? Because we need to know whether:

  • The user still exists.
  • The account is active.
  • The user has been disabled.

JWT signature verification proves that the token is authentic. It does not guarantee that the associated user is still allowed to access the application.

We’ll implement this in our authentication controller/base controller.

Next milestone: Registration and Login APIs, including password verification with has_secure_password, issuing JWTs, Rails rate_limit and request specs. We’ll also ensure that a user cannot access another user’s tasks by changing an ID.

Create Task Manager app: Setup backend – Rails models, tables, enums and add Rspec Tests

Create the User model

Now let’s start building our actual Rails application.

I want to start with the User model rather than Task, because our application will have JWT authentication and every task must belong to an authenticated user. We’ll introduce RefreshSession when we implement JWT refresh tokens.

Install bcrypt

Rails provides has_secure_password, which uses bcrypt for password hashing.

Uncomment this to backend/Gemfile: gem "bcrypt", "~> 3.1.7" and do bundle install

Why bcrypt?

We should never store users’ actual passwords in the database. Instead, bcrypt hashes the password using a salt. Rails provides password authentication functionality through has_secure_password. We’ll explore password hashing, verification and authentication in detail when implementing JWT login.

Generate User model

rails g model User email:string password_digest:string
      invoke  active_record
      create    db/migrate/20261117085319_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb

Notice invoking rspec, because we configured rspec generators. Notice that we’re using password_digest, not password. has_secure_password provides a virtual password attribute and stores its hash in password_digest

Review the migration

Make these database-level changes:

  • email must not be NULL.
  • password_digest must not be NULL.
  • Add a unique, case-insensitive index for email.
class CreateUsers < ActiveRecord::Migration[8.1]
  def change
    create_table :users do |t|
      t.string :email, null: false
      t.string :password_digest, null: false

      t.timestamps
    end

    add_index :users, "lower(email)", unique: true, name: :idx_users_lower_email
  end
end

Run:

rails db:prepare -t 

Inspect db/schema.rb. You should see the users table with the expected columns and index.

Checklist

  • Add bcrypt to Gemfile.
  • Generate User model.
  • Add database constraints.
  • Add case-insensitive unique email index.
  • Run migrations successfully.
  • Inspect schema.rb.
  • Commit changes.

We’ll introduce has_secure_password, email normalization, validations, described_class, build_stubbed vs new and proper model specs. We’ll also begin understanding how RSpec interacts with ActiveRecord and PostgreSQL.

Let’s implement our first real Rails model behaviour and write meaningful RSpec tests against it.

User model, validations and password security

in User model add: has_secure_password

What does this provide? When you assign: user.password = "my-secret-password" Rails automatically generates a bcrypt password digest and stores it in: user.password_digest

It also provides: user.authenticate("my-secret-password")

The behaviour is:

InputResult
Correct passwordReturns the user object
Incorrect passwordReturns false

Important things to understand:

has_secure_password provides these validations automatically:

  • Password must be present when creating a new record.
  • Password cannot exceed 72 bytes.
  • Password confirmation is checked when you supply password_confirmation.

It does not enforce a minimum password length or complexity. We’ll discuss our password policy when implementing registration. Also, bcrypt’s 72-byte limit is a byte limit, not necessarily a 72-character limit.

Normalize the email address

onsider these inputs:

"Abhilash@Example.com"
" abhilash@example.com "
"ABHILASH@EXAMPLE.COM"

We want to store a consistent representation: abhilash@example.com

Rails provides an attribute normalization API. Add this to your model:

normalizes :email, with: ->(email) { email.strip.downcase }

Why use normalizes?

  • Normalization happens when an attribute is assigned or validated.
  • It keeps email representation consistent.
  • You don’t need to remember to call .strip.downcase in every controller.

Rails has supported normalizes since Rails 7.1.

Add email validations

Add validations for:

  • Email presence.
  • Email uniqueness, case-insensitive.

Use Rails validations rather than implementing custom validation methods for these requirements.

Important architectural distinction:

We’re using two protections for uniqueness:

  1. ActiveRecord uniqueness validation – provides a useful validation error to the application.
  2. PostgreSQL unique index – protects the database against concurrent duplicate inserts.

Neither replaces the other.

Note: Our earlier lower(email) unique index is important here. The validation and database constraint must enforce the same case-insensitive uniqueness rule.

Understand the complete model behaviour

Your model should now have three responsibilities:

User
 ├── Password security
 │    └── has_secure_password
 │
 ├── Email normalization
 │    └── normalizes
 │
 └── Email validations
      ├── presence
      └── case-insensitive uniqueness

Prepare RSpec model testing

described_class

Instead of writing: User.new(...)

inside every example, we can use: described_class.new(...)

When we write: RSpec.describe User do

described_class refers to User

Why is this useful?

Imagine we later rename the model or move the spec. Using described_class reduces unnecessary references to the class name.

Open:backend/spec/models/user_spec.rb

new vs create!

We’ll use native ActiveRecord methods for now, before introducing FactoryBot.

MethodBehaviour
User.newCreates an unsaved ActiveRecord object
User.createCreates and attempts to persist a record
User.create!Persists or raises an exception if validations fail
user = User.new(email: "test@example.com")
user.persisted? # false

# whereas:
user = User.create!(...)
user.persisted? # true

For a model uniqueness test, we need a persisted record to check against. We’ll introduce FactoryBot later and understand build, create and build_stubbed.

RSpec assignment

Implement these tests. We can use subject, let, context and before wherever appropriate. Refer: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/

Exercise 1 – Valid user

Create a user with a valid email and password. Verify that the user is valid.

Exercise 2 – Email presence

Test what happens when:

  • Email is missing.
  • Email is an empty string.

Verify the appropriate validation error.

Exercise 3 – Email uniqueness

This is important. Create a user with: abhilash@example.com

Then attempt to create another user using: ABHILASH@EXAMPLE.COM

Verify that the second user is invalid. Why are we testing this?

Because email uniqueness should be case-insensitive.

Exercise 4 – Email normalization

Pass this value: " Abhilash@Example.com " Verify that the resulting email is: abhilash@example.com

Also test that uppercase input is normalized.

Exercise 5 – Password digest

Create a user with a password.

Verify:

  • password_digest is present.
  • password_digest does not equal the original password.
  • The password digest is stored, not the plain-text password.

Exercise 6 – Password authentication

Test both scenarios:

Correct password:
user.authenticate("correct-password")
Expected: returns the user

Incorrect password:
user.authenticate("wrong-password")
Expected: returns false

Exercise 7 – Password confirmation

Try assigning:

password = "password123"
password_confirmation = "different-password"

Verify that the user is invalid.

Remember: Rails only checks confirmation when password_confirmation is supplied.

User Spec spec/models/user_spec.rb:

require 'rails_helper'

RSpec.describe User, type: :model do
  let(:valid_user) { described_class.create!(email: "email@example.com", password: "password@1") }
  let(:non_persisted_user) { described_class.new(email: "  EMAIL@example.com  ", password: "Pass12#") }

  describe "validations" do
    context "valid user" do
      it "check valid user" do
        expect(non_persisted_user.valid?).to be_truthy
      end
  
      it "check email, password presence" do
        non_persisted_user.valid?
        expect(non_persisted_user.email).not_to be_empty
        expect(non_persisted_user.password).not_to be_empty
      end
    end

    context "invalid user" do
      it "missing email, password, password digest" do
        invalid_user = described_class.new(email: "", password: "")
        invalid_user.valid?
        expect(invalid_user.errors.full_messages).to include("Email can't be blank")
        expect(invalid_user.errors.full_messages).to include("Password can't be blank")
        expect(invalid_user.errors.full_messages).to include("Password digest can't be blank")
      end

      it "throw error email not unique" do
        valid_user
        invalid_user = described_class.new(email: " EMAIL@EXAMPLE.com", password: "password@1")
        invalid_user.valid?
        expect(invalid_user.errors.full_messages).to include("Email has already been taken")
      end
    end
  end

  describe "email normalization" do
    it "email normalization when validation happens" do
      non_persisted_user.valid?
      expect(non_persisted_user.email).to eq("email@example.com")
    end

    it "email normalization when assignment" do
      new_user = described_class.new
      new_user.email = "  MYEMAIL@GMAIL.COM "
      expect(new_user.email).to eq("myemail@gmail.com")
    end

    it "checks email normalized after saving" do
      non_persisted_user.save!
      expect(non_persisted_user.email).to eq("email@example.com")
    end
  end

  describe "Passwords" do
    context "Passwords authentication" do
      it "checks valid authentication if email and password provided" do
        result = valid_user.authenticate("password@1")
        expect(result).to equal(valid_user)
      end
  
      it "checks invalid authentication if wrong password given" do
        result = valid_user.authenticate("wrong-pass12")
        expect(result).to be(false)
      end
    end

    context "Password digest" do
      it "checks password digest is present" do
        expect(valid_user.password_digest).not_to be_empty
      end

      it "password digest does not equal the original password" do
        expect(valid_user.password_digest).not_to eq(valid_user.password)
      end

      it "The password digest is stored, not the plain-text password" do
        # expect(valid_user.password_digest).
      end
    end
  end
end

Q): How does let caching work?

This is an important concept.

RSpec memoizes let values per example (it), not across examples.

Consider:

let(:user) do
  puts "Creating user"
  described_class.create!(
    email: "test@example.com",
    password: "password123"
  )
end

Now imagine three examples:

it "example 1" do
  user
  user
end

it "example 2" do
  user
end

it "example 3" do
  user
end

The execution looks like this:

Example 1
   |
   v
Access user
   |
   v
Execute let block (1st time)
   |
   v
Cache the result
   |
   v
Access user again
   |
   v
Return cached object
   |
   v
Example ends - cache discarded

Example 2
   |
   v
Access user
   |
   v
Execute let block again (2nd time)
   |
   v
Cache the result
   |
   v
Example ends - cache discarded

Example 3
   |
   v
Access user
   |
   v
Execute let block again (3rd time)
   |
   v
Cache the result

So the output will be:

Creating user
Creating user
Creating user

Key concept The user object is cached within one example, but a new object is created for every subsequent example that accesses user.

What about let!?

Exactly the same memoization, but with eager evaluation.

let!(:user) do
  puts "Creating user"
  described_class.create!(...)
end

The block executes automatically before every example.

Even if you never reference user inside the example, it is still created.

Behaviourletlet!
Lazy evaluationYesNo
Automatic evaluationNoYes
Memoized within exampleYesYes
Cached across examplesNoNo
Executes again in next exampleWhen referencedAlways

Important: RSpec’s memoization is unrelated to Rails caching (Rails.cache) or database caching. It only caches the helper’s return value for the current example.

There is too much test cases for a small user model snippet. So how big the test will be if the user model evolves and becomes big.

Q) Is it worth spending these much time spending test examples or do we write only the major ones in real world?

We deliberately wrote more examples than we’d probably write for such a small model in a real project. The objective was to teach you RSpec matchers, setup, validations, memoization and password testing.

In real-world development, we don’t write tests for every possible combination just to increase the test count.

What do we actually test in production?

My recommendation is:

Test behaviour and business rules, not every line of code.

For our current User model, I’d consider these the important behaviours:

BehaviourShould we test?Reason
Email presenceYesBusiness requirement
Email normalizationYesData consistency
Case-insensitive uniquenessYesBusiness requirement
Password authenticationYesSecurity-critical
Incorrect passwordYesSecurity-critical
Password hashingYesSecurity-critical
Password confirmationIf enabledRegistration requirement
Every possible email formatNot necessarilyAvoid redundant tests
Every possible password stringNoTest meaningful boundaries

Notice that we don’t necessarily need a separate example for every assertion. For example, password hashing could be tested in one example:

  1. Create a user.
  2. Reload the user from the database.
  3. Verify that the password digest exists.
  4. Verify that the original password isn’t stored as the password attribute.
  5. Verify that authentication still works.

That’s one meaningful behaviour test rather than several fragmented tests.

How do we decide whether to write a separate test?

I generally follow these principles.

Rule 1: Different behaviour deserves different examples.

For example:

  • Correct password authenticates.
  • Incorrect password doesn’t authenticate.

These should be separate examples because they represent different outcomes.

Rule 2: Don’t test every framework feature.

For example, Rails already implements has_secure_password. We don’t need to test every internal operation of bcrypt. We need to test that our application uses it correctly.

Rule 3: Test security boundaries thoroughly.

Authentication, authorization, permissions, data ownership and input validation deserve more attention than simple getters and setters.

Rule 4: Test regressions.

Suppose a developer changes email normalization and accidentally removes .downcase. A good test should catch that regression.

Regression testing is a type of software testing performed to ensure that a recent code change, bug fix, new feature, or system update has not broken existing functionality.

When is it Performed?

  • You typically trigger regression testing in situations such as:
  • After bug fixes: To confirm that fixing one issue did not inadvertently create another.
  • After adding new features: To make sure new code plays nicely with legacy code.
  • After code refactoring: When the underlying code is cleaned up or restructured without changing its external behavior.
  • Before a major release: As a final baseline check across critical user journeys

What happens when a model becomes bigger?

Imagine our User model eventually supports:

class User < ApplicationRecord
  has_secure_password

  has_many :tasks
  has_many :refresh_sessions

  # Email normalization
  # Password validations
  # Account status
  # Roles
  # Account locking
  # Email verification
end

We shouldn’t put every possible test into one enormous example group.

We organize them by behaviour:

spec/
└── models/
    └── user_spec.rb

Inside:

RSpec.describe User, type: :model do
  describe "validations" do
    # Relevant validation examples
  end

  describe "associations" do
    # Association behaviour
  end

  describe "authentication" do
    # Password authentication
  end

  describe "email normalization" do
    # Normalization behaviour
  end

  describe "account locking" do
    # Account locking behaviour
  end
end

If the model becomes excessively complex, we should also consider extracting responsibilities into service objects or dedicated domain components instead of continuing to grow the model indefinitely.

What about 100% test coverage?

Don’t chase 100% coverage blindly.

Consider:

  • 100% line coverage doesn’t guarantee that your application works correctly.
  • A test can execute a line without checking its result.
  • Critical security behaviour deserves tests even if the overall coverage is already high.

I prefer meaningful test coverage over a high coverage percentage.

My recommendation for our project

We’ll follow a practical testing strategy.

Our testing strategy

Model specs: Validate business rules, model behaviour, associations and important edge cases.

Request specs: Test HTTP requests, authentication, authorization, status codes and JSON responses.

Service specs: Test independent business logic such as JWT generation, verification and refresh-token rotation.

Integration testing: Verify that important application workflows work together.

Introduce FactoryBot

Let’s introduce FactoryBot, one of the most commonly used tools in Rails testing. Our goal is to stop manually constructing User records in every RSpec example and create reusable test data instead.

FactoryBot setup and fundamentals

1. Why do we need FactoryBot?

Consider our existing RSpec code:

let(:valid_user) do
  User.create!(
    email: "email@example.com",
    password: "password@1"
  )
end

Imagine we have 50 test examples involving users. We might repeatedly write: User.create!(email: "...", password: "...")

This creates several problems:

  • Repeated test data.
  • Duplicate attribute definitions.
  • Difficulties maintaining tests when models evolve.
  • Unintentional duplicate email addresses.
  • Complex setup when models have associations.

FactoryBot solves this by allowing us to define reusable object blueprints called factories.

Install FactoryBot:

Official Gem Repo: https://github.com/thoughtbot/factory_bot_rails

Open backend/Gemfile. Add:

group :development, :test do
  gem "factory_bot_rails"
end

Why both groups?

  • test: We need FactoryBot to create test data.
  • development: Enables Rails generator integration, so Rails can generate factories when we generate models.

Do: bundle install

Configure FactoryBot with RSpec

We want to use: build(:user)
create(:user)

Instead of writing: FactoryBot.build(:user)
FactoryBot.create(:user)

Both are valid. We’ll enable the shorter syntax in RSpec. Create a support directory:

mkdir -p spec/support
touch spec/support/factory_bot.rb

In spec/support/factory_bot.rb, add this configuration:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Now open: spec/rails_helper.rb

Find this line (it may be commented out):

# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

Uncomment it. See the comment above. This ensures that our support files are loaded when RSpec starts. This is fine for us as we only load the Rspec configuration from the support folder.

Why use spec/support?

As our testing infrastructure grows, we’ll add reusable configuration and helpers here.

For example:

spec/
├── factories/
├── models/
├── requests/
├── services/
├── support/
│   └── factory_bot.rb
├── rails_helper.rb
└── spec_helper.rb

Create your first factory

Create the file: mkdir -p spec/factories
touch spec/factories/users.rb

Our first factory will represent a valid User. The structure will look like this:

FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@example.com" }

    password { "password@1" }
  end
end

Let’s understand each part.

FactoryBot.define – Container for our factory definitions.

factory :user – Defines a factory named user.

FactoryBot automatically identifies the corresponding Rails model as User.

sequence(:email) – Generates a unique email each time the factory is evaluated.

For example:

user1@example.com
user2@example.com
user3@example.com

Why do we need sequences?

Remember our unique email constraint in PostgreSQL. Without sequences, creating multiple users with the same email could result in uniqueness validation errors.

password – Provides a default password that satisfies our current User model requirements.

One important practice: a factory should provide the minimum attributes necessary to create a valid object. We’ll introduce optional attributes and traits later.

Understand FactoryBot build strategies

This is probably the most important FactoryBot concept.

FactoryBot supports four commonly used strategies.

1. build(:user)

In memory user = build(:user)

  • Creates a User instance.
  • Does not save it to PostgreSQL.
  • Does not execute database persistence callbacks.
  • Returns an unsaved ActiveRecord object.

Equivalent in concept to: User.new(...)

Use when: Testing validations and model behaviour without requiring database persistence.

2. create(:user)

Persisted user = create(:user)

  • Builds a User instance.
  • Saves it to PostgreSQL.
  • Runs validations and persistence callbacks.
  • Returns a persisted record.

Equivalent in concept to: User.create!(...)

Use when: Testing uniqueness, database queries, associations and persistence-related behaviour.

3. build_stubbed(:user)

Stubbed object user = build_stubbed(:user)

  • Does not save the record to PostgreSQL.
  • Assigns simulated persistence attributes such as an ID.
  • Stubs database-related behaviour.

Use when: You need an object that behaves like a persisted record but don’t need actual database interaction.

Be careful: it isn’t a substitute for a real persisted record in integration or database-dependent tests.

4. attributes_for(:user)

Hash only attributes = attributes_for(:user)

Returns an attribute hash rather than a User object.

Use when: Building request payloads or testing API input handling.

An important performance consideration: unnecessary database writes make large test suites slower. Choose the lightest strategy that actually tests the behaviour you care about.

FactoryBot traits and list factories

Now let’s learn two features that become particularly useful when application models grow.

1. List factories: build_list and create_list

Suppose we need five users for a test.

Without list factories:

user1 = create(:user)
user2 = create(:user)
user3 = create(:user)
user4 = create(:user)
user5 = create(:user)

FactoryBot provides a better way.

build_list – users = build_list(:user, 5) – Creates five User objects without saving them.

create_list – users = create_list(:user, 5) – Creates five User records and persists them to PostgreSQL.

MethodObjectsDatabase
build_list5No records
create_list55 records

Both methods return arrays.

Exercise

Create a new spec: touch spec/learning/factory_bot_lists_spec.rb Write two examples.

Exercise A – build_list – Create three users and verify:

  • Array contains three users.
  • None of the users is persisted.
  • All three emails are unique.

Exercise B – create_list – Create three users and verify:

  • Array contains three users.
  • All three are persisted.
  • All three have unique IDs
describe "Factory Bot: Build list" do
    context "create three users and verify" do
      it "contains 3 users" do
        users = build_list(:user, 3)
        expect(users.size).to eq(3)
      end
      it "3 users are not persisted and emails are unique" do
        users = build_list(:user, 3)
        emails = []
        users.each do |user|
          emails << user.email
          expect(user.persisted?).to eq(false)
        end
        expect(emails.uniq.size).to eq(3)
      end
    end
  end

  describe "Factory Bot: Create list" do
    context "create three users and verify" do
      it "contains 3 users" do
        users = create_list(:user, 3)
        expect(users.size).to eq(3)
      end
      it "all users are persisted and have unique ids" do
        users = create_list(:user, 3)
        user_ids = []
        users.each do |user|
          user_ids << user.id
          expect(user.persisted?).to eq(true)
        end
        expect(user_ids.uniq.size).to eq(3)
      end
    end
  end

FactoryBot traits

Now imagine our User model supports password confirmation. We may need different user states in different tests:

  • User with matching password confirmation.
  • User with mismatched password confirmation.
  • User without password.

We don’t want to create a separate factory for every scenario. This is where traits are useful. A trait represents a reusable variation of an existing factory. For example:

build(:user, :with_password_confirmation) Or: build(:user, :with_invalid_password_confirmation)

Both reuse the same :user factory but apply different attributes.

Assignment

Open: spec/factories/users.rb Add two traits:

TraitBehaviour
:with_password_confirmationSets password confirmation equal to password
:with_invalid_password_confirmationSets a different password confirmation

Don’t add any new model validations. Rails’ has_secure_password already supports password confirmation validation when confirmation is supplied.

Test these traits

In your new spec file, create examples that:

  1. Build a user with matching password confirmation and verify that it is valid.
  2. Build a user with mismatched password confirmation and verify that it is invalid.
  3. Verify that the second user has the expected validation error.

Important: Use build, not create for these tests. We are testing validation behaviour, not database persistence.

# spec/models/user_spec.rb

context "With Traits" do
      it "verify with password confirmation" do
        user = build(:user, :with_password_confirmation)
        expect(user.valid?).to eq(true)
      end
      it "verify with invalid password confirmation" do
        user = build(:user, :with_invalid_password_confirmation)
        expect(user.valid?).to eq(false)
        expect(user.errors.full_messages).to include("Password confirmation doesn't match Password")
      end
    end

Understanding when to use traits vs overrides

This distinction is useful in real projects.

RequirementPreferred approach
Change email for one exampleAttribute override
Create multiple userscreate_list
Reuse an admin user stateTrait
Reuse an inactive user stateTrait
Change password for one exampleAttribute override
Reuse a specific authentication stateTrait

Don’t create traits for every possible attribute combination. Traits are most useful for meaningful, reusable object states.

Create the Task model and database relationship

Now we’re moving into the actual Task Management application.

Our first important domain relationship:

  • One User can create multiple Tasks.
  • Every Task belongs to exactly one User.

Database relationship

User 1 : N Tasks -> user_id (FK) – Each task stores the ID of its owner.

1. Decide our Task attributes

Let’s start with a simple schema.

ColumnTypeConfiguration
idbigintPrimary key
user_idbigintForeign key, NOT NULL
titlestringNOT NULL
descriptiontextNullable
statusintegerNOT NULL, default 0
created_atdatetimeAutomatically generated
updated_atdatetimeAutomatically generated

For the status, we’ll eventually support:

  • pending
  • in_progress
  • completed

Why integer?

Rails supports enums that map readable status names to integer values in the database. We’ll implement the enum separately and understand its advantages and pitfalls, particularly why explicitly mapping enum values is important.

Generate the Task model

From your backend directory:

bin/rails generate model Task title:string description:text status:integer user:references

Because we’ve configured RSpec generators, you should get (notice invoking Rspec and FactoryBot):

Inspect the actual migration and make the necessary adjustments.

Configure the associations

Open: app/models/user.rb – Add the one-to-many association.
Open: app/models/task.rb – Inspect the generated belongs_to association.

# migration
class CreateTasks < ActiveRecord::Migration[8.1]
  def change
    create_table :tasks do |t|
      t.string :title, null: false
      t.text :description
      t.integer :status, null: false, default: 0
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end

# user model
class User
  has_many :tasks, dependant: :destroy
  ....
end

# task model
class Task < ApplicationRecord
  belongs_to :user
end
 

We’ll discuss the difference between destroy, delete, dependent: :delete_all and database-level cascading deletion later.

Do: rails db:migrate -t, check database table details:

FactoryBot associations: User and Task

This is particularly useful because real applications rarely have isolated models. Most models have relationships, and our tests need to create related records efficiently.

1. Create the Task factory

Open: spec/factories/tasks.rb

Our Task model has:

  • title
  • description
  • status
  • user_id

We want every generated Task to have an associated User. Your factory should follow this structure:

FactoryBot.define do
  factory :task do
    title { "Improve Product" }
    description { "Improve the product page by minimizing dependancies" }

    association :user
  end
end

Understand association :user

FactoryBot understands that the Task factory needs a User factory to construct its associated User. It automatically resolves the :user factory. You could also write: user. But I prefer association :user for now.

How does FactoryBot handle associated objects?

This is an important concept. FactoryBot uses the parent’s build strategy for associations by default.

Consider: task = build(:task)

Expected behaviour:

build(:task)
     |
     v
Build Task object
     |
     v
Build associated User
     |
     v
Return Task
     |
     v
Neither record persisted

Now consider: task = create(:task)

Expected behaviour:

create(:task)
     |
     v
Create associated User
     |
     v
Create Task with user_id
     |
     v
Both records persisted

This is controlled by FactoryBot’s use_parent_strategy configuration, which defaults to true

An important mistake to avoid:

Don’t write this inside the Task factory: user { create(:user) }

Why? Even when you call build(:task), this explicitly creates and persists the User. You lose the advantage of build. Use association :user instead.

Attribute override for associations

Let’s say we already have a User and want to assign that specific User to a Task.

We can override the association:

user = create(:user)

task = build(:task, user: user)

Now the Task belongs to the User you supplied. This is useful when testing ownership, permissions and authorization later. For example, we’ll eventually have multiple users, each with their own tasks.

RSpec assignment

open: backend/spec/models/task_spec.rb

Use:

RSpec.describe Task, type: :model do
  describe "associations" do
    it "belongs_to" do
      task = create(:task)
      expect(task.user).to be_truthy
      expect(task.user_id).to be_truthy
    end
    it "has_many" do
      user = create(:user)
      create_list(:task, 3, user: user)

      expect(user.tasks.count).to eq(3)
    end
  end
end

Implement these four examples.

Exercise 1 – Build associated User

Use build(:task). Verify:

  • Task is not persisted.
  • Task has a User object.
  • Associated User is not persisted.

Exercise 2 – Create associated User

Use create(:task). Verify:

  • Task is persisted.
  • Associated User is persisted.
  • task.user_id matches task.user.id.

Exercise 3 – Override association

Create a User separately. Pass that User into build(:task, user: user). Verify that the Task belongs to the exact User object supplied.
Hint: Think about the difference between eq and equal.

Exercise 4 – Multiple Tasks for one User

Create one User and three Tasks associated with that User. Verify:

  • There are three Tasks.
  • All three belong to the same User.
  • All three Tasks are associated with the User through the has_many relationship.
    • Hint: create_list(:task, 3, user: user).

Run your tests: rspec spec/models/task_spec.rb --format documentation

If your test database hasn’t been prepared since the Task migration: You could use bin/rails db:test:prepare

Task model validations

Now let’s implement actual business rules for our Task model.

1. Define our validation requirements

For our application, let’s establish these rules:

AttributeRequirement
titleRequired
titleMaximum 120 characters
descriptionOptional
descriptionMaximum 2,000 characters
userRequired
statusWe’ll handle separately using Rails enums

Why these requirements?

  • A task without a title doesn’t provide meaningful information.
  • A title should be reasonably short because it appears in the task list.
  • Description should be optional because sometimes users only need a task title.
  • Every task must belong to a user.

Rails automatically validates the presence of the associated user by default. You generally don’t need to add another validates :user, presence: true. Remember that we also have a database foreign key and NOT NULL constraint. These protect the database independently of model validations.

class Task < ApplicationRecord
  belongs_to :user

  validates :title, presence: true, length: { maximum: 120 }
  validates :description, length: { maximum: 2000 }, allow_blank: true
end

Write Task model specs

Open: backend/spec/models/task_spec.rb

Organize the tests using:

RSpec.describe Task, type: :model do
  describe "validations" do
    it "a valid task" do
      task = build(:task)
      expect(task.valid?).to eq(true)
    end

    it "title presence, check nil, empty, space contents" do
      task = build(:task, title: nil)
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
      task = build(:task, title: '')
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
      expect(task.errors.full_messages).to include("Title is too short (minimum is 2 characters)")
      task = build(:task, title: '  ')
      task.valid?
      expect(task.errors.full_messages).to include("Title can't be blank")
    end
    
    it "title length" do
      task = build(:task, title: "my " * 40) # 120 chars
      expect(task.valid?).to eq(true)
      task = build(:task, title: "my " * 40 + "q") # 121 chars
      expect(task.valid?).to eq(false)
    end
    
    it "valid description" do
      task = build(:task, description: nil)
      expect(task.valid?).to eq(true)
      task = build(:task, description: "my" * 1000) # 2000 chars
      expect(task.valid?).to eq(true)
      task = build(:task, description: "my" * 1000 + 'm') # 2001 chars
      expect(task.valid?).to eq(false)
    end
    
    it "user association" do
      task = build(:task, user: nil)
      expect(task.valid?).to eq(false)
    end
  end
end

Use FactoryBot for test data.

Exercise 1 – Valid task
Exercise 2 – Title presence – Title is nil. Title is an empty string.
Exercise 3 – Title length
Exercise 4 – Description – Description is nil – valid. Description is empty – valid.

Exercise 1 – User has many tasks – Create a user and three associated tasks. Verify that:

  • The user has three tasks.
  • All tasks belong to that user.
  • All returned tasks are persisted.

Exercise 2 – Destroy dependent tasks – Create a user and three associated tasks. Destroy the user. Verify:

  • The user is destroyed.
  • All three tasks are destroyed.
  • The task records no longer exist in the database.

Hint: You can use reload carefully or Task.exists? to verify database state.

Exercise 3 – Task belongs to User – Create a task. Verify:

  • task.user returns a User.
  • task.user_id matches task.user.id.
  • The association can be reloaded successfully.



Let’s move to an important Rails feature: ActiveRecord Enums.

task.user returns a User.

task.user_id matches task.user.id.

Rails Enums

We’ll implement task statuses using Rails enums and learn how Rails maps human-readable values to integers in PostgreSQL.

1. Why do we need enums?

Our Task model has a status integer column. Without enums, we might write:

task.status = 0 # Pending
task.status = 1 # In progress
task.status = 2 # Completed


What’s the problem? Imagine another developer reads this:

if task.status == 2
end

What does 2 mean? We need readable values instead. Rails enums solve this problem.

Define our Task statuses

We’ll support three statuses:

Pending 0 – Task hasn’t been started yet.

In progress 1 – Task is currently being worked on.

Completed 2 – Task has been completed.

Open: backend/app/models/task.rb

enum :status, {
  pending: 0,
  in_progress: 1,
  completed: 2
}, validate: true

This is the Rails 8.1 enum syntax. Official documentation: ActiveRecord::Enum – Rails 8.1.4

Why use an explicit hash instead of an array?

Rails also supports: enum :status, [:pending, :in_progress, :completed]

This automatically maps values based on their positions:

pending => 0
in_progress => 1
completed => 2

However, consider adding another status in the middle later. The integer mapping could change, potentially corrupting the interpretation of existing records.

My recommendation: Always use explicit integer mappings for database-backed enums in production applications. Keep existing mappings stable.

Understand what Rails generates automatically

This is where enums become interesting. Once you define the enum, Rails generates several methods automatically.

A. Predicate methods

You can check the current status:

task.pending?
task.in_progress?
task.completed?

Example:

task = Task.new
task.status
# "pending"

task.pending?
# true

task.completed?
# false

The initial status comes from our database default of 0

Bang methods

Rails generates methods that update and persist the status:

task.in_progress!
task.completed!
task.pending!

For example:

task = Task.create!(title: "Learn Rails", user: user)

task.completed!

This updates the database. Remember: the ! methods save the record through update!. They are different from simply assigning an attribute.

Scopes

Rails automatically generates scopes:

Task.pending
Task.in_progress
Task.completed

These return ActiveRecord relations. For example: Task.pending

Conceptually generates a query similar to:

SELECT * FROM tasks WHERE status = 0;

You can also use negative scopes: Task.not_completed

These are particularly useful later when implementing the task filters in React.

Reading and updating status

You can assign a status using its symbolic value:

task.status = :completed

Or:

task.update!(status: :in_progress)

Reading the status returns its string representation:

task.status
# "in_progress"

However, the underlying database value is an integer.

Accessing the mapping

Rails also provides:

> Task.statuses
=> {"pending" => 0, "in_progress" => 1, "completed" => 2}

Useful when you need to inspect the database mapping or build queries.

Important: What does validate: true do?

Notice that we used: validate: true This is an important option. By default, assigning an unsupported enum value raises an ArgumentError immediately.

For example:

task.status = :unknown

But with validate: true:

task.status = :unknown

task.valid?
# false

Rails adds an inclusion validation instead.

Why did we choose this?

Eventually, our React application will send status values to Rails through API requests. Suppose React sends:

{
  "status": "invalid_status"
}

We want to handle this as a model validation failure and return a proper 422 Unprocessable Entity response, rather than accidentally returning a server error because of an exception.

This is a deliberate choice for our API. Rails documents both behaviours. Check: https://api.rubyonrails.org/v8.1.4/classes/ActiveRecord/Enum.html

RSpec assignment

Now let’s test the actual enum functionality. Open: backend/spec/models/task_spec.rb

Add a new group:

describe "status" do
    it "default status" do
      task = build(:task)
      expect(task.status).to eq('pending')
      expect(task.pending?).to eq(true)
      expect(task.completed?).to eq(false)
    end

    it "status assignment" do
      task = build(:task, status: :in_progress)
      expect(task.status).to eq('in_progress')
      expect(task.in_progress?).to eq(true)
      expect(task.pending?).to eq(false)
    end

    it "status bang methods" do
      task = create(:task)
      task.completed!
      expect(task.status).to eq('completed')
      expect(task.completed?).to eq(true)
      expect(task.pending?).to eq(false)
      task.reload # confirm db persistence
      expect(task.completed?).to eq(true)
    end

    it "Enum mapping" do
      status = described_class.statuses
      expect(status['pending']).to eq(0)
      expect(status['in_progress']).to eq(1)
      expect(status['completed']).to eq(2)
    end

    it "Invalid status" do
      task = build(:task)
      task.status = :invalid
      expect(task.valid?).to eq(false)
      not_included_msg = "Status is not included in the list"
      expect(task.errors.full_messages).to include(not_included_msg)
      task.status = nil
      task.valid?
      expect(task.errors.full_messages).to include(not_included_msg)
    end

    it "Enum scopes" do
      pending = create(:task)
      in_progress = create(:task, status: :in_progress)
      completed = create(:task, status: :completed)
      expect(Task.pending).to contain_exactly(pending)
      expect(Task.in_progress).to contain_exactly(in_progress)
      expect(Task.completed).to contain_exactly(completed)
    end
  end

Implement these six scenarios.

Exercise 1 – Default status

Build a new Task without specifying its status. Verify:

  • task.status returns "pending".
  • task.pending? returns true.
  • task.completed? returns false.

Remember, this depends on the database default being 0.

Exercise 2 – Status assignment

Build a Task with: status: :in_progress Verify:

  • Its status is "in_progress".
  • in_progress? returns true.
  • pending? returns false.

Exercise 3 – Bang methods

Create a persisted Task and call: task.completed! Verify:

  • completed? returns true.
  • The updated status is "completed".
  • Reloading the record still gives "completed".

Why do we reload? We want to verify that the database was actually updated.

Exercise 4 – Enum mapping

Verify the mapping returned by: described_class.statuses

Check that each status maps to the expected integer.

Exercise 5 – Invalid status

Build a Task and assign: task.status = :invalid_status

Because we enabled validate: true, verify that:

  • No ArgumentError is raised.
  • task.valid? returns false.
  • A status validation error is present.

Also check what happens when status is explicitly assigned nil.

Exercise 6 – Enum scopes

Create three Tasks:

  • One pending.
  • One in progress.
  • One completed.

Verify that:

Task.pending
Task.in_progress
Task.completed

each returns only the matching Task. Use contain_exactly or match_array where appropriate.

One database configuration check

Before running the tests, inspect your original Task migration and schema.rb. We should have: t.integer "status", default: 0, null: false

This is important for two reasons:

  • Every new task starts as pending.
  • The database doesn’t allow a NULL status.

If you already configured this earlier, no changes are necessary. If the migration has already been applied and the constraint is missing, generate a new migration rather than silently changing an already-applied migration.

Q) Why do you use Enums? and integer-backed enums instead of storing strings directly?

Rails enums provide a convenient interface for managing a fixed set of values, including generated predicate methods, scopes and update methods. Integer-backed enums also use less storage and generally produce more compact indexes than string-backed equivalents.

However, string-backed enums are also supported. The choice depends on database readability, maintainability and performance requirements. I wouldn’t choose integer-backed enums solely for performance without measuring the actual workload.

We shouldn’t use integers just because Rails supports enums.

You can absolutely store "pending", "in_progress" and "completed" directly as strings in PostgreSQL. There are legitimate reasons to choose either approach.

Let’s understand the actual trade-offs.

1. Three ways to store status

There are three approaches worth understanding.

Option A: Store strings directly

Database:

tasks
--------------------------------
id | title       | status
--------------------------------
1  | Learn Rails | pending
2  | Learn React | in_progress
3  | Write tests | completed

Migration: t.string :status, default: "pending", null: false

You can query directly: Task.where(status: "pending")

But you need to implement your own validation:

validates :status, inclusion: {
in: %w[pending in_progress completed]
}

And implement any convenience methods or scopes yourself.

Advantages:

  • Database values are human-readable.
  • Easy to inspect using SQL.
  • No integer mapping to maintain.
  • Adding a new status is straightforward.

Option B: Rails integer-backed enum

This is what we’re currently implementing.

Database:

tasks
--------------------------------
id | title       | status
--------------------------------
1  | Learn Rails | 0
2  | Learn React | 1
3  | Write tests | 2

Rails model:

enum :status, {
  pending: 0,
  in_progress: 1,
  completed: 2
}, validate: true

Rails translates between the integer and its corresponding symbolic value.

For example:

task.status
# "pending"

task.status = :completed

task.save!

task.status
# "completed"

You also get:

task.pending?
task.completed!

Task.pending
Task.completed

These methods and scopes are generated by Rails.

Option C: Rails string-backed enum

Here’s something interesting: you can use Rails enum functionality without storing integers!

enum :status, {
  pending: "pending",
  in_progress: "in_progress",
  completed: "completed"
}, validate: true

Your database column must be a string. Now you get the same convenience methods:

task.pending?
task.completed!

Task.pending
Task.completed

But PostgreSQL stores the actual strings.

Rails supports both integer-backed and string-backed enums. Its documentation notes that string-backed enums will likely result in slower database queries.

2. Does storing integers improve performance?

Yes, there can be storage and indexing advantages. But let’s understand how significant they are.

A. Storage size

PostgreSQL uses:

For our three statuses:

StatusString lengthApprox. PostgreSQL storage
pending7 bytes8 bytes
completed9 bytes10 bytes
in_progress11 bytes12 bytes
Integer mapping4 bytes4 bytes

Approximate column value storage, excluding row and index overhead.

Imagine you have 10 million tasks.

For illustration, assuming every record has the same status:

StorageApproximate size
Integer (4 bytes)38.1 MiB
String pending (8 bytes)76.3 MiB

That difference becomes meaningful at scale. For our small Task Management application, however, the difference is practically irrelevant.

B. Index performance

This is where your question becomes interesting. Suppose we create an index:

add_index :tasks, :status

With an integer-backed enum, the database indexes integer values.

With a string-backed enum, the database indexes string values.

Both can use PostgreSQL B-tree indexes.

Integer index keys are more compact and integer comparisons are generally cheaper than string comparisons. However, don’t assume that integer storage automatically makes every query faster.

Consider: SELECT * FROM tasks WHERE status = 0;

versus: SELECT * FROM tasks WHERE status = 'pending';

Both can use an appropriate index.

An important point: Our status column has only three possible values. This is called low cardinality.

If 60% of your records are pending, an index on status alone might not be particularly useful. PostgreSQL may prefer a sequential scan because so many rows match.

We need to consider actual queries and their execution plans. For our application, a query such as: Task.where(user_id: current_user.id, status: :pending)

might benefit from a composite index: add_index :tasks, [:user_id, :status]

We shouldn’t add it blindly, though. We’ll later examine EXPLAIN ANALYZE and understand whether it helps.

3. What is the actual benefit of Rails enums?

In my opinion, this is the more important reason to use them. Regardless of whether you choose integer or string storage, Rails enums provide a convenient interface for working with a fixed set of values.

Without enums, you might write:

task.status == "completed"

Task.where(status: "pending")

And define your own scopes and methods.

With Rails enums:

task.completed?

task.completed!

Task.pending
Task.in_progress
Task.completed

You also get the status mapping through: Task.statuses

So enums provide:

  1. A defined set of allowed values.
  2. Generated predicate methods.
  3. Generated update methods.
  4. Generated database query scopes.
  5. Consistent mapping between application values and stored values.

This is why enums are useful even when storage performance isn’t important.

One distinction: a Rails enum is not the same thing as PostgreSQL’s native ENUM data type. Rails’ integer-backed enum is an application-level mapping to a normal integer column.

4. What would I choose for our Task Management application?

Here’s the recommendation.

ConsiderationInteger-backedString-backed
Storage efficiencyBetterSlightly larger
Index key sizeSmallerLarger
Database readabilityLess readableMore readable
Rails generated methodsYesYes
Adding statusesMaintain mappingsMore straightforward
SQL debuggingRequires mappingDirectly readable

For our project, both are perfectly reasonable.

I would actually lean towards string-backed Rails enums for this particular application if we were prioritizing database readability and simplicity over storage optimization.

We only have three statuses, and there’s no meaningful performance bottleneck here.

However, we’ll retain the integer-backed implementation for our current exercise so you understand the conventional Rails approach, its generated methods, its mapping and its trade-offs.

One takeaway for our project: Enums are primarily about representing and managing a fixed set of domain values conveniently. Integer storage is an additional benefit, not the fundamental reason to use enums.

Implement Task Manager application with Ruby on Rails backend, React frontend, Postgresql, Rspec, Docker and Github Actions

Let’s create an application for managing Tasks that are created by different users. Let’s use React UI for quick data response. The app consists of CRUD operations of Tasks, User Authentication using JWT-Tokens, User Authorization for their particular tasks.

Technology stack

Here’s the list of technology stack we use in our application.

LayerTechnologyPurpose
BackendRuby on Rails 8.1+REST API
DatabasePostgreSQLPersistent storage
FrontendReactUI
LanguageTypeScriptStatic typing
Build toolViteFrontend development/build
UI libraryFluent UI React v9Components and styling
HTTPFetch API initiallyAPI communication
Server cacheTanStack QueryAPI data caching
Global stateRedux ToolkitShared client-side state
Testing backendRSpecAPI and model tests
Testing frontendVitest + React Testing LibraryComponent tests
ContainersDocker + Docker ComposeContainerization
CI/CDGitHub ActionsAutomation and deployment

Check our ruby current version.

$ ruby -v

ruby 3.4.1 (2024-12-25 revision 48d4efcb85)

Check the security patches and updates of our version.

https://www.ruby-lang.org/en/downloads/releases

Then update the latest compatible version.

$ mise use -g ruby@3.4.12

(2026-10-23 revision 366f5fdc00)

To uninstall Ruby using mise, run mise uninstall ruby@ to delete a specific installed version.

$ mise uninstall ruby@3.4.1

Install latest ruby version that you need.

Switch between versions globally:

$ mise use -g ruby@3.4.12

$ mise use -g ruby@4.0.9

Check all needed versions exists:

ruby -v
gem -v
rails -v
node -v
npm -v
psql --version

Check Postgres versions available here: https://www.postgresql.org/download/macosx/

Download the one of the latest one if you have currently installed the old version.

$ brew install postgresql@18

Installing postgresql@18
==> Pouring postgresql@18--18.7.arm64_tahoe.bottle.tar.gz
Warning: postgresql@18 was installed but not linked because postgresql@14 is already linked.
To link this version, run:
brew link postgresql@18

$ brew link postgresql@18
Unlinking /opt/homebrew/Cellar/postgresql@14/14.17_1... 2165 symlinks removed.
Linking /opt/homebrew/Cellar/postgresql@18/18.7... 812 symlinks created.
$ psql --version
psql (PostgreSQL) 18.7 (Homebrew)

Update node js:

$ node -v
v24.14.0

install the latest Long-Term Support release

$ nvm install --lts
Installing latest LTS version.
Downloading and installing node v26.13.1...
Downloading https://nodejs.org/dist/v26.13.1/node-v26.13.1-darwin-arm64.tar.xz...
Computing checksum with sha256sum
Checksums matched!
Now using node v26.13.1 (npm v11.20.0)

Create app folder:

$ mkdir rails-react-task-manager
$ cd rails-react-task-manager
$ git init -b main

We want to manage the backend, frontend, Docker configuration and CI/CD workflows in one repository.

Update ruby gems:

A new release of RubyGems is available: 4.0.20 → 4.0.24!
See https://github.com/ruby/rubygems/blob/v4.0.24/CHANGELOG.md for the changes since 4.0.20.
Run `gem update --system 4.0.24` to update your installation

Install Rails:

check rails newest versions: https://rubygems.org/gems/rails/versions

$ gem install rails -v '~> 8.1.0'

Note: Pessimistic version constraint. Using -v “~> 8.1.0” installs the latest patch release within the 8.1 series (such as 8.1.4.1) while avoiding unintended jumps to future minor or major versions

Reopen the shell and check:

Create a github repository

name it: rails-react-task-manager

$ git remote add origin git@github.com:<username>/rails-react-task-manager.git

Problem 1:

The first problem I faced was the command rails new already has the folders: .git, .github, .gitattributes, .gitignore etc inside rails app.

So when I try to push the rails app:

git add backend/
error: 'backend/' does not have a commit checked out
error: unable to index file 'backend/'
fatal: adding files failed

This happens because Rails automatically initializes a Git repository when you run rails new.

Solution: Keep only one Git repository

Since we’re building a monorepo, we want Git initialized only at the project root.

Remove only the nested Git metadata:

rm -rf backend/.git
TypeWhen to Use It Example
choreUpgrading packages, libraries, or runtime versions chore: update Node.js version or chore(deps): bump lodash
featAdding a new feature or capability for the user.feat: add user login via OAuth
fixPatching a bug in the application code.fix: resolve crash on checkout page
refactorRestructuring production code without changing its behavior.refactor: simplify auth helper logic
docsUpdating READMEs, comments, or API guides.docs: add setup instructions
styleFixing formatting, whitespace, or missing semicolons.style: format files with Prettier
testAdding or updating unit and integration tests.test: add unit tests for cart total
build / ciMaking dedicated changes to build systems or CI pipelines (used by teams that prefer stricter categories over chore).ci: cache node_modules in pipeline

Problem 2:

Accessing the Rails url at: http://localhost:3000/

Started GET "/" for ::1 at 2026-11-15 

ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
)
Caused by: PG::InvalidParameterValue (ERROR:  invalid value for parameter "TimeZone": "UTC"
)

Information for: ActiveRecord::StatementInvalid (PG::InvalidParameterValue: ERROR:  invalid value for parameter "TimeZone": "UTC"
):

Solution: check which PostgreSQL server is actually running

psql --version
brew services list
brew services stop postgresql@14
brew services restart postgresql@18
# then do
rails db:prepare -t # recommended

Restart the rails server. Also check:

curl -i http://localhost:3000/up

Install RSpec

Add RSpec to Gemfile

group :development, :test do
  gem "rspec-rails", "~> 8.1"
end

Install the gem

cd backend
bundle install
bundle exec rspec --version

Generate RSpec configuration

 rails g rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb
FileResponsibility
.rspecDefault command-line options for RSpec
spec_helper.rbGeneral RSpec configuration
rails_helper.rbRails-specific test configuration

Important distinction:

spec_helper.rb can be used for tests that don’t require Rails.

rails_helper.rb loads the Rails application and integrates Rails testing functionality.

Verify:

bundle exec rspec
No examples found.

Finished in 0.00022 seconds (files took 0.05449 seconds to load)
0 examples, 0 failures

Minitest is still present: Your Rails application probably already has: backend/test/. That’s because Rails generated its default Minitest structure. We’ll configure Rails generators to use RSpec automatically, so that when we generate a model, Rails creates: spec/models/task_spec.rb instead of: test/models/task_test.rb. We’ll also decide how to handle the existing Minitest files cleanly.

Configure Rails generators to use RSpec

Currently, Rails uses Minitest as its default testing framework. For example, when you generate a model: bin/rails generate model Task title:string, Rails normally generates: app/models/task.rb
test/models/task_test.rb

But we want: app/models/task.rb
spec/models/task_spec.rb

RSpec Rails integrates with Rails generators to do exactly this.

Open: backend/config/application.rb and add:

config.generators do |g|
  g.test_framework :rspec
end

Important: This does not remove Minitest or disable its test runner. It changes the default generator behaviour.

We don’t want to generate our actual Task model just to test the configuration.

Instead, use Rails --pretend option:

rails g model Task title:string --pretend
      invoke  active_record
      create    db/migrate/20261115171837_create_tasks.rb
      create    app/models/task.rb
      invoke    rspec
      create      spec/models/task_spec.rb

Rspec Structure:

spec/
├── models/
│   └── task_spec.rb
│
├── requests/
│   └── api/
│       └── v1/
│           └── tasks_spec.rb
│
├── services/
│   └── authentication/
│
├── jobs/
├── factories/
│
├── spec_helper.rb
└── rails_helper.rb

For our Rails API, we’ll primarily use request specs instead of controller specs. A request spec tests the application from the HTTP client’s perspective. This lets us test the complete API behaviour rather than testing controller methods in isolation. RSpec Rails recommends request specs as the higher-level alternative to controller specs.

For example:

HTTP Request
    ↓
Router
    ↓
Controller
    ↓
Authentication
    ↓
Authorization
    ↓
Model / Database
    ↓
HTTP Response

Understand the structure of an RSpec test

An RSpec test typically consists of four important building blocks:

RSpec syntaxPurpose
RSpec.describeDefines the top-level example group
describeGroups related examples
contextDescribes a particular condition or scenario
itDefines an individual test example
expectDefines an expectation
toSpecifies the expected matcher

Let’s look at a simple example.

RSpec.describe "RSpec basics" do
  describe "equality matcher" do
    it "compares two values" do
      result = 2 + 3

      expect(result).to eq(5)
    end
  end
end

Understand each line

RSpec.describe "RSpec basics" – Creates an example group. This is the outermost container for our tests.

describe "equality matcher" – Groups tests related to equality. You can nest multiple describe blocks to organize tests logically.

it "compares two values" – Defines an individual test example. The string describes the expected behaviour. RSpec uses it when displaying test results.

expect(result).to eq(5) – This is the actual expectation.

  • expect(result) – the actual value.
  • to – tells RSpec we’re checking a positive expectation.
  • eq(5) – matcher checking whether the actual value equals 5 using Ruby’s == operator.

If the expectation fails, RSpec reports a failure with the actual and expected values.

Understand RSpec matchers

Matchers are one of the most important parts of RSpec.

They determine how RSpec compares actual and expected values.

Here are some commonly used matchers:

MatcherPurposeExample
eqValue equality (==)eq(10)
beObject identity (equal?)be(true)
includeCollection contains valueinclude("Rails")
be_nilChecks nilbe_nil
be_emptyChecks empty collectionbe_empty
be_truthyChecks truthinessbe_truthy
be_falseyChecks falsinessbe_falsey
matchRegular expression matchingmatch(/rails/i)
raise_errorChecks raised exceptionraise_error(ArgumentError)

A particularly important distinction: expect("Rails").to eq("Rails")

This checks value equality. Whereas: expect(object).to be(other_object)

This checks whether both references point to the same object. Don’t confuse eq and be. You can also write negative expectations: expect(result).not_to eq(10) This verifies that the result isn’t equal to 10.

One principle to remember: Good tests should make the behaviour obvious, minimize duplicated setup and remain independent of one another. That’s the mindset I want you to develop while learning RSpec.

Understand describe vs context

They look similar, but they serve slightly different organizational purposes. Consider a future Task model.

RSpec.describe Task do
  describe "validations" do
    context "when title is present" do
      # Examples go here
    end

    context "when title is missing" do
      # Examples go here
    end
  end
end

Preferred convention:

  • describe: What behaviour are we testing?
  • context: Under what circumstances are we testing it?
  • it: What should happen?

Technically, describe and context create the same kind of RSpec example group. The difference is semantic and improves readability.

hands-on exercise

Let’s create a temporary learning spec. We aren’t creating the Task model or touching the database yet. From your backend directory:

mkdir spec/learning
touch spec/learning/rspec_basics_spec.rb

Start with the previous equality example. Now add your own examples to cover these requirements:

Exercise 1 – Equality

Write an example that checks whether 10 + 20 equals 30.

Exercise 2 – Collection

Given: languages = ["Ruby", "JavaScript", "Python"]

Write an expectation that verifies the array includes "Ruby".

Exercise 3 – Nil

Given a variable whose value is nil, verify that it is nil.

Exercise 4 – Boolean

Given a variable whose value is false, verify that it is exactly false.

Exercise 5 – Negative expectation

Verify that the languages array does not include "Java".

Execute your tests: bundle exec rspec spec/learning/rspec_basics_spec.rb

For more readable output: bundle exec rspec spec/learning/rspec_basics_spec.rb --format documentation , The documentation formatter displays the example descriptions and their results.

Refer:

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/equality

https://rspec.info/features/3-13/rspec-expectations/built-in-matchers/include

https://rspec.info/features/3-12/rspec-core/helper-methods/let

RSpec.describe "Rspec Basics learning" do
  describe "Equality" do
    let(:languages) { ["Ruby", "JavaScript", "Python"] }

    it "check addition" do
      expect(10 + 20).to eq(30)
    end

    it "include in the list" do
      expect(languages).to include "Ruby"
    end

    it "checks nil value" do
      nil_value = nil
      expect(nil_value).to be_nil
    end

    it "checks false value" do
      false_value = false
      true_value = true
      expect(false_value).to be false
      expect(false_value).to be_falsey
      expect(true_value).to be_truthy
      expect(true_value).to be true
    end

    it "checks negative expectation" do
      expect(languages).not_to include "Scala" 
    end
  end
end

# run
$ rspec spec/

Note:
be false vs be_falsey These are different expectations.

expect(false).to be false 
expect(false).to be_falsey
expect(nil).to be_falsey
expect(true).to be_truthy

be_truthy accepts anything other than false or nil. be false checks that the value is exactly false. be_falsey accepts either false or nil. let is lazily evaluated and memoized within an individual example.

We’ll apply these concepts to our first actual Rails model spec. No need to rush into FactoryBot yet. We should understand native RSpec first.

RSpec hooks: before, after, let and let!

This is one of the most frequently used parts of RSpec in real Rails projects. When writing model and request specs, we often need to prepare test data before executing an example.

For example:

  • Create a user before testing authentication.
  • Create a task before testing task updates.
  • Prepare some data before testing associations.
  • Clean up resources after an example.

RSpec provides hooks and helper methods for this.

before hook

RSpec.describe "Task" do
  before do
    puts "Running before hook"
  end

  it "checks something" do
    puts "Running example"
  end

  it "checks something else" do
    puts "Running another example"
  end
end

# output
Running before hook
Running example

Running before hook
Running another example

before executes before every example by default. These are equivalent:

before do
  # Setup
end

# and

before(:each) do
  # Setup
end

When do we use it?

When every example needs some common setup. For example, imagine we need a variable initialized before each test.

Imagine we have 10 test examples and every example requires the same initial setup.

# Without hooks, you might repeat:

it "example 1" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

it "example 2" do
  languages = ["Ruby", "JavaScript"]
  # Test logic
end

# This creates unnecessary duplication. RSpec provides hooks to solve this problem.

Understand let vs before

This distinction is particularly important.

beforelet
Setup hookDefines a helper method
Executes automaticallyExecutes only when referenced
Runs before every example by defaultEvaluates once per example
Useful for setup actionsUseful for reusable test data

after hook: after executes after each example.

after(:each) do
  puts "Cleaning up"
end

Typical use cases:

  • Cleaning up temporary resources.
  • Restoring modified environment variables.
  • Closing external resources.
  • Removing temporary files.

RSpec Rails and transactional tests will handle much of our database cleanup automatically, so we shouldn’t manually delete every test record in after

let – lazy evaluation

Let’s understand its behaviour: let(:languages) { ["Ruby", "JavaScript", "Python"] } . And if you call it multiple times within the same example, RSpec reuses its cached value. This is called lazy evaluation and memoization.

Hands-on exercise

Let’s create another learning spec: touch spec/learning/rspec_setup_hooks_spec.rb

RSpec.describe "RSpec setup hooks" do
  let(:execution_log) { [] }

  let(:languages) do
    execution_log << :languages_created
    ["Ruby", "JavaScript", "Python"]
  end

  before(:each) do
    execution_log << :before_hook
  end

  # Write your examples here
  it "Test lazy evaluation" do
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variable and check lazy evaluation when referenced" do
    expect(languages).to include("Ruby")
    puts "execution_log: #{execution_log}"
  end
  
  it "Access let variables twice within this example and verify lazy loading" do
    expect(languages).to include("Python")
    expect(languages).not_to include("Rust")
    puts "execution_log: #{execution_log}"
  end
end

We’ll now cover three important RSpec concepts that you’ll use extensively when writing Rails model specs and request specs:

  1. let! – eager evaluation.
  2. subject – defining the primary object under test.
  3. before(:all) vs before(:each) – setup lifecycle and execution order.

RSpec execution lifecycle

1. let vs let!

We already understand let. let!(:user) { "Abhilash" } The ! changes the behaviour.

# let - Lazy

Start example
    |
    v
Before hook
    |
    v
Execute example
    |
    v
Access user?
   /    \
  Yes     No
  |       |
Evaluate  Never
# let! - Eager

Start example
    |
    v
Execute let! setup
    |
    v
Before hooks (according to declaration order)
    |
    v
Execute example

Technically, let! is implemented by defining a let helper and registering a before hook that invokes it.

When should we use let!?

Consider a Rails model spec. Suppose we want to test whether a user has three tasks. We need those three tasks to exist before the example executes. This is a good use case for let!. let!(:task) { create(:task) }

We’ll eventually use FactoryBot’s create method here.

My recommendation: Prefer let by default. Use let! when the setup must happen before the example, regardless of whether the helper is explicitly accessed.

2. subject – the primary object under test

This is another important RSpec concept. Suppose we’re testing a method that normalizes a task title. Instead of repeatedly creating or referencing the main result, we can define it using subject.

subject(:normalized_title) do
  title.strip.downcase
end

Now we can use: expect(normalized_title).to eq("learn rails")

Why use subject?

Imagine testing a Task model with many examples. The primary object being tested is usually a Task instance. We can define:

subject(:task) do
  Task.new(title: "Learn Rails")
end

Then use: expect(task).to be_valid

Notice the difference:

letsubject
Defines reusable test dataDefines the primary object under test
Can define multiple helpersUsually one primary subject per example group
Access using its nameAccess using its name or subject
Lazy and memoizedLazy and memoized

A named subject such as subject(:task) also creates a helper called task.

What is the implicit subject?

RSpec also provides a default subject. For example:

RSpec.describe Array do
  it "starts empty" do
    expect(subject).to be_empty
  end
end

When the described class is an Array, RSpec’s implicit subject is a new instance of that class. You can also explicitly use: subject { described_class.new }

described_class refers to the class being tested.

Best practice: Prefer named subjects when they improve readability, especially in model specs.

3. before(:each) vs before(:all)

This is particularly important when working with database records.

HookExecutionState
before(:each)Before every exampleIsolated per example
before(:all)Once before the example groupShared across examples

before without arguments is equivalent to before(:each).

Example: before each

before(:each) do
  puts "Before each example"
end

Suppose there are three examples. Output:

Before each example
Example 1

Before each example
Example 2

Before each example
Example 3

Example: before all

before(:all) do
  puts "Before all examples"
end

Output:

Before all examples

Example 1
Example 2
Example 3

Important: Be careful with before(:all) and ActiveRecord

This is something I want you to remember for Rails development. RSpec Rails normally manages database transactions around individual examples. before(:all) runs outside that normal per-example transaction lifecycle. Consequently, database records created in before(:all) can leak between examples or require manual cleanup.

It can also result in shared mutable objects, making tests order-dependent.

My recommendation: For our Rails model and request specs, prefer let, let! and before(:each).

Use before(:all) only when you have a specific reason and understand its lifecycle implications.

Understand hook execution order

Suppose we have:

RSpec.describe "Outer" do
  before do
    puts "Outer before"
  end

  describe "Inner" do
    before do
      puts "Inner before"
    end

    it "runs example" do
      puts "Example"
    end
  end
end

What do you think the output will be?

It is: Outer before → Inner before → Example

The general rule is:

  • Parent group hooks run before nested group hooks.
  • Hooks registered within the same group run in declaration order.
  • let! internally registers a before hook at the point where it is declared, so declaration order can matter.

Practical assignment

Let’s combine what we’ve learned.

Let’s create another learning spec: touch spec/learning/rspec_lifecycle_spec.rb Implement the following exercises.

Exercise 1 – let!

Create an execution log. Define one let and one let!. Both should append different symbols to the execution log when evaluated.

Write an example verifying that:

  • The let! value is evaluated before the example.
  • The let value is not evaluated until referenced.

Exercise 2 – subject

Define a named subject called normalized_title. Its implementation should remove leading/trailing whitespace and convert a string to lowercase.

Verify that: " LEARN RAILS " produces: "learn rails"

Exercise 3 – Memoization

Access your named subject twice. Use an execution counter or log to verify that its block is evaluated only once within the same example.

Exercise 4 – Hook ordering

Create nested outer and inner example groups with before hooks. Predict and then verify the execution order. Run:

bundle exec rspec spec/learning/rspec_lifecycle_spec.rb --format documentation


RSpec.describe "Test rspec lifecycle hooks" do
  let(:execution_log) { [] }
  let(:title) { "  LEARN RSPEC  " }

  subject(:normalized_title) do
    execution_log << :subject_executed
    puts "subject execution_log: #{execution_log}"
    title.downcase.strip
  end

  let(:animal) do
    execution_log << :animal
    "Lion"
  end

  let!(:bird) do
    execution_log << :bird
    "Eagle"
  end

  describe "let and let!" do
    it "test let! evaluation" do
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
      expect(execution_log.count(:subject_executed)).to eq(0)
    end
  end

  describe "test subject lazyness" do
    it "call subject and check the counter" do
      normalized_title
      subject
      expect(execution_log.count(:subject_executed)).to eq(1)
    end
  end

  before do
    p "Outer hook"
  end

  describe "Test hook ordering" do
    before do
      p "Inner hook"
    end
    it "test inner hook" do
      expect(execution_log.count(:subject_executed)).to eq(0)
      expect(execution_log.count(:animal)).to eq(0)
      expect(execution_log.count(:bird)).to eq(1)
    end
  end
end

This is a good demonstration of eager versus lazy evaluation.

Remember this distinction:

LocationSyntax
Declarationsubject(:normalized_title) { ... }
Access inside examplenormalized_title
Access using default namesubject

A few observations before moving on:

  1. subject(:normalized_title) is lazy. It executes only when accessed.
  2. Calling normalized_title and then subject accesses the same memoized subject. The block executes only once per example.
  3. let!(:bird) executes automatically before each example, including examples in nested groups.
  4. let(:animal) never executes in your current examples because you don’t access it.

Integrate AI with Rails: Day 10 – RAG Part 2: embeddings

Let’s move directly into RAG Part 2: embeddings.

One important correction before we code: the free model list you fetched earlier contains no free embedding model slug. OpenRouter currently lists liquid/lfm2.5-embedding-350m as a free embedding model, producing 1,024-dimensional vectors. OpenRouter’s embeddings API is OpenAI-compatible, so we can use the same Ruby SDK/base URL. (OpenRouter)

That means our existing vector(1536) column is the wrong dimension for the free embedding model we’ll use. We’ll fix that now.

RAG Part 2 – Ai::EmbeddingService

Our target architecture:

DocumentChunk
      │
      ▼
Ai::EmbeddingService
      │
      ▼
OpenRouter Embedding API
      │
      ▼
1024-dimensional vector
      │
      ▼
document_chunks.embedding

Then later:

User question
      ↓
Embedding
      ↓
pgvector similarity search
      ↓
Relevant chunks
      ↓
PromptBuilder
      ↓
LLM

Step 1 – Change the vector dimension

We originally created:

t.vector :embedding, limit: 1536

But our free model produces 1,024 dimensions.

Generate a migration:

bin/rails g migration ChangeDocumentChunkEmbeddingDimension

Open the migration and use:

class ChangeDocumentChunkEmbeddingDimension < ActiveRecord::Migration[8.1]
  def change
    remove_column :document_chunks, :embedding, type: :vector

    add_column :document_chunks, :embedding, :vector, limit: 1024
  end
end

Since our chunks don’t contain embeddings yet, removing and recreating the column is fine.

Run:

bin/rails db:migrate

Verify:

bin/rails dbconsole
\d document_chunks

You want:

embedding | vector(1024)

Then:

\q

Step 2 – Add the embedding model constant

Open:

app/services/ai/client.rb

Keep your existing chat models and add:

EMBEDDING_MODEL = "liquid/lfm2.5-embedding-350m:free"

So conceptually:

class Ai::Client
  MODELS = [
    "minimax/minimax-m3:free",
    "google/gemma-4-31b-it:free",
    "nvidia/nemotron-3-super-120b-a12b:free"
  ].freeze

  EMBEDDING_MODEL = "liquid/lfm2.5-embedding-350m"

  BASE_URL = "https://openrouter.ai/api/v1"

  # ...
end

Notice that this model is not a :free slug in the model ID you should send. OpenRouter currently lists this embedding model itself as free.

Check: https://openrouter.ai/models?output_modalities=embeddings


Step 3 – Add embeddings to Ai::Client

Add:

def embed(text:)
  response = @client.embeddings.create(
    model: EMBEDDING_MODEL,
    input: text
  )

  {
    embedding: response.data.first.embedding,
    model: response.model,
    input_tokens: response.usage&.prompt_tokens
  }
end

So your client now has two responsibilities:

chat()
embed()

Both communicate with the same OpenRouter endpoint, but use different models/endpoints. OpenRouter provides an OpenAI-compatible /embeddings API for this. (OpenRouter)

Step 4 – Test the raw embedding request

Open Rails console:

bin/rails c

Then:

client = Ai::Client.new

Now:

result = client.embed(
  text: "Ruby on Rails is a web application framework."
)

Inspect:

result.keys

You should get:

[:embedding, :model, :input_tokens]

Now:

result[:embedding].length

You should get:

1024

This is an important RAG checkpoint.

You’ve just proven:

text
↓
embedding model
↓
1024 numbers

Now inspect the first few values:

result[:embedding].first(5)

You’ll see floating-point numbers.

Don’t worry about the actual values. Their position in vector space is what matters.

Step 5 – Create Ai::EmbeddingService

Now we introduce the application-level service.

Create:

app/services/ai/embedding_service.rb

Use:

class Ai::EmbeddingService
  def initialize(ai_client: Ai::Client.new)
    @ai_client = ai_client
  end

  def call(text:)
    result = @ai_client.embed(text: text)

    result[:embedding]
  end
end

Why create another service when Ai::Client already has embed?

Because these are different responsibilities:

Ai::Client

How do I communicate with OpenRouter?

Ai::EmbeddingService

How does our application generate an embedding?

That distinction becomes useful once we introduce:

  • chunking
  • batch embeddings
  • document indexing
  • retries
  • persistence

Step 6 – Generate an embedding for a real chunk

We already created our Ruby Guide document.

Open console:

bin/rails c

Then:

chunk = DocumentChunk.first

Check:

chunk.content

Now:

embedding = Ai::EmbeddingService.new.call(
  text: chunk.content
)

Verify:

embedding.length

Expected:

1024

Step 7 – Save the vector

Now:

chunk.update!(embedding: embedding)

Then:

chunk.reload

And:

chunk.embedding.length

You should get:

1024

We now have our first actual vector stored in PostgreSQL.

Error: I cannot update embedding vector column with Ruby Array embedding data

I have tested to storing the embedding. But it seems to be Rails does not know / there is a Type mismatch for embedding ruby array data and db vector data type

➜  ai_assistant git:(main) ✗ rails c
Loading development environment (Rails 8.1.3.1)
ai-assistant(dev):001> chunk = DocumentChunk.first

embedding = Ai::EmbeddingService.new.call(
  text: chunk.content
)

> chunk.update!(embedding: embedding)
(ai-assistant):5:in '<compiled>': can't quote Array (TypeError)

          raise TypeError, "can't quote #{value.class.name}"
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Check the solution here: https://railsdrop.com/update-embedding-vector-column-with-ruby-array-embedding-data-from-llm/

Step 8 – Embed all three chunks

We currently have:

Chunk 1 → Ruby blocks
Chunk 2 → Ruby modules
Chunk 3 → Ruby classes

Run:

service = Ai::EmbeddingService.new

Then:

DocumentChunk.find_each do |chunk|
  chunk.update!(
    embedding: service.call(text: chunk.content)
  )
end

Now:

DocumentChunk.where(embedding: nil).count

should return:

0

And:

DocumentChunk.count

should return:

3

Step 9 – Verify directly in PostgreSQL

Run:

bin/rails dbconsole

Then:

SELECT
  id,
  chunk_index,
  vector_dims(embedding)
FROM document_chunks;

Expected:

 id | chunk_index | vector_dims
----+-------------+------------
 1  | 0           | 1024
 2  | 1           | 1024
 3  | 2           | 1024

This is a very useful RAG sanity check.

Step 10 – Now perform our FIRST semantic search

This is the exciting part.

Take a query:

"What allows Ruby code to be reused?"

Generate its embedding:

query_embedding = service.call(
  text: "What allows Ruby code to be reused?"
)

Now we need PostgreSQL to compare that vector against all the chunk vectors.

pgvector provides operators including cosine distance (<=>) and inner product; cosine distance is a common choice for semantic search. (OpenRouter)

Run this in Rails console:

results = DocumentChunk
  .where.not(embedding: nil)
  .order(
    Arel.sql(
      "embedding <=> '#{query_embedding}'"
    )
  )
  .limit(3)

Why we’re stopping at this exact point

We’ve now completed the embedding generation side:

Document
   ↓
Chunk
   ↓
EmbeddingService
   ↓
OpenRouter
   ↓
1024-d vector
   ↓
PostgreSQL

The next piece is the actual retrieval:

Question
   ↓
Query embedding
   ↓
pgvector
   ↓
ORDER BY cosine distance
   ↓
Top K chunks

That is the point where RAG becomes real.

Then we’ll build Ai::VectorSearchService and make the first semantic search against PostgreSQL – the most important practical RAG step after embeddings.


to be continued ..

Integrate AI with Rails: Day 10 – RAG with PostgreSQL + pgvector – part 1

We’ll move quickly, but this time keep each milestone runnable. Since you already have PostgreSQL and a working Rails 8.1 app, pgvector is a natural fit: it stores vectors alongside normal PostgreSQL data and supports cosine similarity plus exact and approximate nearest-neighbor search. (GitHub)

Step 13A – Install and enable pgvector

1. Check your PostgreSQL version

Run:

psql --version

Then check whether the extension is already installed:

bin/rails dbconsole

Inside PostgreSQL:

SELECT extname, extversion
FROM pg_extension
WHERE extname = 'vector';

If you get a row

For example:

 vector | 0.8.6

you’re ready.

If you get no rows

You need to install the extension on your PostgreSQL installation.

Since you’re on macOS, if PostgreSQL was installed via Homebrew:

brew install pgvector

The pgvector project currently documents Homebrew installation for PostgreSQL 17/18 formulas. (GitHub)

Then restart PostgreSQL if required by your installation:

brew services restart postgresql@14

Use your actual PostgreSQL version if different.

Step 13B – Enable pgvector in Rails

Once PostgreSQL has the extension available, exit psql:

\q

Generate the migration:

bin/rails generate migration EnablePgvector

Open the migration and use:

class EnablePgvector < ActiveRecord::Migration[8.1]
  def change
    enable_extension "vector"
  end
end

Then:

bin/rails db:migrate

Error: PG::UndefinedFile: ERROR: could not open extension control file "/opt/homebrew/share/postgresql@14/extension/vector.control": No such file or director

This error occurs because the pgvector extension is not installed or cannot be found in the directory of your specific Homebrew-managed PostgreSQL 14 installation.

Do:

# 1. Clone the pgvector repository
cd /tmp
git clone --branch v0.8.6 https://github.com/pgvector/pgvector.git
cd pgvector

# 2. Explicitly point to your PostgreSQL 14 pg_config binary
export PG_CONFIG=/opt/homebrew/opt/postgresql@14/bin/pg_config

# 3. Build and install the extension
make
make install # may need sudo

# Verify the Installation: after the installation completes successfully, check if the vector.control file is present in the target directory
ls /opt/homebrew/share/postgresql@14/extension/vector.control

Verify:

➜  ai_assistant git:(main) rails dbconsole
psql (14.17 (Homebrew))
Type "help" for help.

ai_assistant_development=# SELECT extname, extversion
FROM pg_extension
WHERE extname = 'vector';
 extname | extversion
---------+------------
(0 rows)

ai_assistant_development=#
\q
➜  ai_assistant git:(main) ✗ brew services restart postgresql@14
Stopping `postgresql@14`... (might take a while)
==> Successfully stopped `postgresql@14` (label: sh.brew.postgresql@14)
==> Successfully started `postgresql@14` (label: sh.brew.postgresql@14)
➜  ai_assistant git:(main) ✗ rails dbconsole
psql (14.17 (Homebrew))
Type "help" for help.

ai_assistant_development=# SELECT extname, extversion
FROM pg_extension
WHERE extname = 'vector';
 extname | extversion
---------+------------
 vector  | 0.8.6
(1 row)

You should now see vector.

Step 13C – Understand our RAG data model

We’re going to introduce two models:

Document
   │
   └── has_many :document_chunks

A document could be:

Ruby Guide

and chunks might be:

Chunk 1 → Ruby blocks
Chunk 2 → Classes
Chunk 3 → Modules
Chunk 4 → Metaprogramming

Each chunk gets its own embedding:

Chunk text
   ↓
Embedding API
   ↓
[0.021, -0.318, ...]
   ↓
PostgreSQL vector column

We’ll use 1536 dimensions initially, because we’ll use an embedding model that produces 1536-dimensional vectors. The actual dimension must match the embedding model you choose; pgvector requires the declared vector dimension to match stored vectors.

Step 13D – Create Document

Run:

bin/rails g model Document title:string source:string

Then:

bin/rails db:migrate

Open:

app/models/document.rb

Change it to:

class Document < ApplicationRecord
  has_many :document_chunks, dependent: :destroy

  validates :title, presence: true
end

Step 13E – Create DocumentChunk

Generate it:

bin/rails g model DocumentChunk \
  document:references \
  content:text \
  chunk_index:integer

Then don’t migrate yet.

We need to add the vector column manually because Rails’ generator doesn’t know which embedding dimension we want.

Open the generated migration and make it:

class CreateDocumentChunks < ActiveRecord::Migration[8.1]
  def change
    create_table :document_chunks do |t|
      t.references :document, null: false, foreign_key: true
      t.text :content, null: false
      t.integer :chunk_index, null: false
      t.vector :embedding, limit: 1536

      t.timestamps
    end

    add_index(
      :document_chunks,
      [:document_id, :chunk_index],
      unique: true
    )
  end
end

Depending on the pgvector Rails integration available in your environment, t.vector may not be recognized. If that happens, we’ll use:

add_column :document_chunks, :embedding, :vector, limit: 1536

instead.

The underlying PostgreSQL representation is:

embedding vector(1536)

which is the pgvector-native type.

Then:

bin/rails db:migrate

As expected gets the error:

-- create_table(:document_chunks)
bin/rails aborted!
StandardError: An error has occurred, this and all later migrations canceled: (StandardError)

undefined method 'vector' for an instance of ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition

Do:

rails g migration addEmbeddingToDocumentChunks

# add
add_column :document_chunks, :embedding, :vector, limit: 1536

# do
rails db:migrate -t

Step 13F – Model association

Open:

app/models/document_chunk.rb

Use:

class DocumentChunk < ApplicationRecord
  belongs_to :document

  validates :content, presence: true
  validates :chunk_index, presence: true
end

Step 13G – Verify the database

Run:

bin/rails dbconsole

Then:

\d document_chunks

You should have:

ai_assistant_development=# \d document_chunks
                                          Table "public.document_chunks"
   Column    |              Type              | Collation | Nullable |                   Default
-------------+--------------------------------+-----------+----------+---------------------------------------------
 id          | bigint                         |           | not null | nextval('document_chunks_id_seq'::regclass)
 document_id | bigint                         |           | not null |
 content     | text                           |           | not null |
 chunk_index | integer                        |           | not null |
 created_at  | timestamp(6) without time zone |           | not null |
 updated_at  | timestamp(6) without time zone |           | not null |
 embedding   | vector                         |           |          |
Indexes:
    "document_chunks_pkey" PRIMARY KEY, btree (id)
    "index_document_chunks_on_document_id" btree (document_id)
    "index_document_chunks_on_document_id_and_chunk_index" UNIQUE, btree (document_id, chunk_index)
Foreign-key constraints:
    "fk_rails_99b41ada32" FOREIGN KEY (document_id) REFERENCES documents(id)

And:

SELECT vector_dims(
  '[1,2,3]'::vector
);

should return:

3

That proves the extension itself is working.

Exit:

\q

Step 13H – Create your first document manually

Before worrying about PDFs, parsers, Sidekiq, etc., let’s prove the RAG data model.

Run:

bin/rails c

Then:

document = Document.create!(
  title: "Ruby Guide",
  source: "manual"
)

Create chunks:

document.document_chunks.create!(
  content: "Ruby blocks are chunks of code passed to methods.",
  chunk_index: 0
)

document.document_chunks.create!(
  content: "Ruby modules allow code to be organized and reused.",
  chunk_index: 1
)

document.document_chunks.create!(
  content: "Ruby classes define objects and their behavior.",
  chunk_index: 2
)

Check:

document.document_chunks.count

Expected:

3

Step 13I – What we’ve built

Our database is now:

documents
----------------
id
title
source

        │
        │ 1 → many
        ▼

document_chunks
----------------
id
document_id
content
chunk_index
embedding

The crucial field is:

embedding

which will eventually contain:

[0.012, -0.883, 0.217, ...]

Int. Checkpoint

You should now be able to explain:

Why don’t we put the embedding on documents?

Because a document is usually too large to embed as one semantic unit.

We split it into chunks and embed each chunk independently:

Document
  ↓
Chunks
  ↓
Embeddings

That lets retrieval find the relevant section instead of returning the entire document.

One important design choice

We’re not adding an HNSW index yet.

An HNSW (Hierarchical Navigable Small World) index is a high-speed graph-based algorithm used to find similar items in large collections of high-dimensional data. It is widely used in vector databases for AI tasks like semantic search and recommendation systems.

pgvector supports exact nearest-neighbor search by default, and approximate indexes such as HNSW and IVFFlat become useful as the dataset grows. HNSW generally offers a strong speed/recall tradeoff but costs more memory and has a slower build.

IVFFlat (Inverted File with Flat compression) is a type of database index used to speed up similarity searches for high-dimensional vectors

For our small learning dataset:

exact search first

Once we have real embeddings and enough data:

HNSW index

We’ll deliberately compare both, which makes a good senior-level discussion.

We’ll create an Ai::EmbeddingService, generate a real embedding through our current provider setup, store it in PostgreSQL, and then perform our first semantic similarity search. That will be the point where we can honestly say we’ve built RAG mechanics rather than just knowing the definition.


to be continued ..

Integrate AI with Rails: AI bootcamp for Developers – Day 6 – Build the Rails Chat UI | Prompt Builder | Chat Memory

In this session we will be building prompt builder to build the prompt that we send to the AI model. We save every conversation in memory and create a chat feature backend architecture.

Step 7 – Conversation Memory + Prompt Builder

Right now our Ai::ChatService sends only:

current user message

So this:

User: My name is Abhilash.
User: What is my name?

doesn’t reliably work as a conversation because the second request doesn’t include the first message.

We need:

Conversation
   ↓
Messages
   ↓
Prompt Builder
   ↓
LLM

1. Change Ai::Client to accept messages

Open:

app/services/ai/client.rb

Change chat from:

def chat(message:)
  ...
end

to:

def chat(messages:)
  response = @client.chat.completions.create(
    model: MODEL,
    messages: messages
  )

  {
    content: response.choices.first.message.content,
    model: response.model,
    input_tokens: response.usage.prompt_tokens,
    output_tokens: response.usage.completion_tokens
  }
end

The client should now know nothing about conversations.

It simply receives:

messages = [
{ role: "system", content: "..." },
{ role: "user", content: "..." },
{ role: "assistant", content: "..." }
]

2. Create PromptBuilder

Create:

app/services/ai/prompt_builder.rb

Add:

class Ai::PromptBuilder
  SYSTEM_PROMPT = <<~PROMPT
    You are a helpful AI assistant.
    Answer clearly and concisely.
    If you are unsure about something, say so.
  PROMPT

  def initialize(conversation:)
    @conversation = conversation
  end

  def build
    [
      {
        role: "system",
        content: SYSTEM_PROMPT.strip
      },
      *@conversation.messages.order(:created_at).map do |message|
        {
          role: message.role,
          content: message.content
        }
      end
    ]
  end
end

Now our database becomes the source of conversation history.

3. Update Ai::ChatService

Change it to:

class Ai::ChatService
  def initialize(
    ai_client: Ai::Client.new,
    prompt_builder_class: Ai::PromptBuilder
  )
    @ai_client = ai_client
    @prompt_builder_class = prompt_builder_class
  end

  def call(conversation:, user_message:)
    conversation.transaction do
      conversation.messages.create!(
        role: :user,
        content: user_message
      )

      messages = @prompt_builder_class
        .new(conversation: conversation)
        .build

      result = @ai_client.chat(messages: messages)

      conversation.messages.create!(
        role: :assistant,
        content: result[:content],
        model: result[:model],
        input_tokens: result[:input_tokens],
        output_tokens: result[:output_tokens]
      )
    end
  end
end

Notice the order:

1. Save user message
2. Load conversation history
3. Build LLM messages
4. Call LLM
5. Save assistant response

4. Test it manually

Run:

bin/rails c

Create a fresh conversation:

conversation = Conversation.create!(title: "Memory Test")

First question:

Ai::ChatService.new.call(
conversation: conversation,
user_message: "My name is Abhilash."
)

Then:

Ai::ChatService.new.call(
conversation: conversation,
user_message: "What is my name?"
)

Now, we should see approximately:

ai-assistant(dev):031> puts conversation.messages.map {|m| "Role: #{m.role}\n Content: #{m.content}" }.join("\n")
Role: user
 Content: My name is Adam Bean
Role: assistant
 Content: Hello Adam Bean! How can I assist you today?

Role: user
 Content: What is my name?
Role: assistant
 Content: Your name is Adam Bean.
=> nil

This is our first real conversation memory implementation.

The LLM did not magically remember the first request.

Rails retrieved the previous messages and sent them again.

That’s a very important int. concept.

5. Understand the architecture

We now have:

                    Conversation
                         │
                         ▼
                    ChatService
                         │
             ┌───────────┴───────────┐
             ▼                       ▼
       PromptBuilder            Ai::Client
             │                       │
             │ messages              │
             └───────────┬───────────┘
                         ▼
                       LLM
                         │
                         ▼
                  Assistant Message
                         │
                         ▼
                    PostgreSQL

The responsibilities are now nicely separated:

Conversation

Persistence.

PromptBuilder

Converts application state into LLM input.

Ai::Client

Talks to the provider.

ChatService

Orchestrates the workflow.

Now we built a solid Rails architecture.

6. Important problem: context growth

Our current implementation sends:

every previous message

on every request.

That eventually becomes:

Message 1
Message 2
...
Message 500
+
New Message

Problems:

  • more tokens
  • more cost
  • more latency
  • eventually context-window limits

This is one of the reasons production AI systems eventually introduce:

conversation summarization
+
recent-message window
+
RAG

Note: We’ll address this later.

Next Major Step – Chat UI

Now we have the backend flow:

User
↓
ChatService
↓
PromptBuilder
↓
LLM
↓
PostgreSQL

The next thing we’ll build is the actual Rails chat interface:

┌──────────────────────────────┐
│ AI Assistant │
├──────────────────────────────┤
│ You: What is Ruby? │
│ │
│ AI: Ruby is... │
│ │
│ You: Explain blocks. │
│ │
│ AI: A block is... │
├──────────────────────────────┤
│ [ Ask something... ] [Send] │
└──────────────────────────────┘

We’ll use Rails + Turbo/Stimulus, then add streaming immediately after that.

That will turn the backend we’ve built into an actual usable AI application.


Let’s move straight to the Chat UI + controller flow, then we can add streaming. We’ll keep this as one cohesive implementation step.

Step 8 – Build the Rails Chat UI

Our backend already does:

Conversation
↓
ChatService
↓
PromptBuilder
↓
Ai::Client
↓
LLM
↓
Message

Now we’ll expose it through HTTP.

8.1 Generate the controller

Run:

bin/rails g controller Conversations show

This gives us a starting point:

app/controllers/conversations_controller.rb
app/views/conversations/show.html.erb

But we also need an endpoint for sending messages.

8.2 Define routes

Open:

config/routes.rb

Use:

Rails.application.routes.draw do
  resources :conversations, only: [:create, :show] do
    resources :messages, only: [:create]
  end

  root "conversations#new"
end

We don’t have new yet, so let’s instead make a simple root action ourselves.

Change to:

Rails.application.routes.draw do
  resources :conversations, only: [:create, :show] do
    resources :messages, only: [:create]
  end

  root "conversations#new"
end

Then generate new:

bin/rails g controller Conversations new

8.3 Conversation controller

Open:

app/controllers/conversations_controller.rb

Use:

class ConversationsController < ApplicationController
  def new
    @conversation = Conversation.new
  end

  def create
    @conversation = Conversation.create!(title: params[:title].presence || "New conversation")

    redirect_to conversation_path(@conversation)
  end

  def show
    @conversation = Conversation.find(params[:id])
    @messages = @conversation.messages.order(:created_at)
  end
end

For now we’re deliberately keeping authentication out of the project.

Later we’ll add authorization when we make this production-oriented.


8.4 Create the messages controller

Run:

bin/rails g controller Messages

Open:

app/controllers/messages_controller.rb

Add:

class MessagesController < ApplicationController
  def create
    conversation = Conversation.find(params[:conversation_id])

    Ai::ChatService.new.call(
      conversation: conversation,
      user_message: params.require(:content)
    )

    redirect_to conversation_path(conversation)
  end
end

The request flow is now:

POST /conversations/:id/messages
↓
MessagesController
↓
Ai::ChatService
↓
LLM

8.5 Build the new conversation page

Open:

app/views/conversations/new.html.erb
<h1>AI Assistant</h1>
<%= form_with model: @conversation, local: true do |form| %>
<%= form.text_field :title, placeholder: "Conversation title" %>
<%= form.submit "Start conversation" %>
<% end %>

Now run:

bin/rails server

Open:

http://localhost:3000

Create a conversation.


8.6 Build the chat page

Open:

app/views/conversations/show.html.erb

Use:

<h1><%= @conversation.title %></h1>

<div id="messages">
  <% @messages.each do |message| %>
    <div>
      <strong><%= message.role.capitalize %>:</strong>
      <%= message.content %>
    </div>
  <% end %>
</div>

<hr>

<%= form_with url: conversation_messages_path(@conversation), method: :post, local: true do |form| %>
  <%= form.text_area :content, rows: 4, placeholder: "Ask something..." %>

  <%= form.submit "Send" %>
<% end %>

Now we have an actual chat interface.


8.7 Test the complete flow

Open:

http://localhost:3000

Create:

Ruby Questions

Then ask:

What is a Ruby block?

The flow should be:

Browser
   ↓
POST /conversations/1/messages
   ↓
MessagesController
   ↓
Ai::ChatService
   ↓
PromptBuilder
   ↓
OpenRouter
   ↓
Assistant response
   ↓
Message saved
   ↓
Redirect
   ↓
Conversation page

You should see:

User: What is a Ruby block?
Assistant: ...

Then ask:

Can you show me an example?

Rails should send the previous conversation history through PromptBuilder.


8.8 One important issue with our current implementation

We’re currently doing:

Ai::ChatService.new.call(...)

inside the HTTP request.

That means:

Browser
  ↓
Rails request
  ↓
wait for LLM
  ↓
save response
  ↓
response

If the LLM takes 8 seconds, our web request can take 8 seconds.

That’s acceptable for our learning version, but not what we ultimately want.

The next step is streaming.


8.9 Also notice an architectural limitation

Right now we’re doing:

redirect_to conversation_path(conversation)

After the LLM finishes.

That’s why the user sees:

wait...
wait...
wait...
complete response

ChatGPT-style applications instead do:

User message
      ↓
LLM starts generating
      ↓
token
      ↓
token
      ↓
token
      ↓
browser updates

We’ll implement that next.


8.10 Add a little UI structure

We can improve the view slightly now:

<h1><%= @conversation.title %></h1>

<div id="messages">
  <% @messages.each do |message| %>
    <article class="message <%= message.role %>">
      <strong><%= message.role.capitalize %></strong>
      <p><%= simple_format(message.content) %></p>
    </article>
  <% end %>
</div>

<%= form_with url: conversation_messages_path(@conversation), method: :post, local: true do |form| %>
  <%= form.text_area :content,
      rows: 4,
      placeholder: "Ask something..." %>

  <%= form.submit "Send" %>
<% end %>

Don’t spend time on styling yet. We care about architecture first.


Fix Chat UI Markdown problem

If we use the following for showing the content:

<p><%= simple_format(message.content) %></p>
Or
<p><%= sanitize(message.content) %></p>

The issue is that sanitize is not a Markdown renderer.

Our LLM is returning Markdown:

**Ruby block**
### Key Characteristics
* Not an object

Rails’ sanitize only sanitizes HTML that already exists. It doesn’t convert Markdown → HTML.

So this:

<%= sanitize(message.content) %>

won’t turn:

**Ruby**

into:

<strong>Ruby</strong>

Recommended approach

For an AI chat application, use:

LLM Markdown
↓
Markdown renderer
↓
HTML
↓
sanitize
↓
Browser

1. Add a Markdown gem

For Rails, a simple choice is commonmarker.

Add to Gemfile:

gem "commonmarker"

Then:

bundle install

2. Create a Markdown helper

Create:

app/helpers/markdown_helper.rb
module MarkdownHelper
  def render_markdown(text)
    html = Commonmarker.to_html(text.to_s)

    sanitize(
      html,
      tags: %w[
        p
        br
        strong
        em
        del
        h1
        h2
        h3
        h4
        ul
        ol
        li
        blockquote
        pre
        code
        a
      ],
      attributes: %w[href title]
    )
  end
end

The important distinction is:

Commonmarker.to_html(...)

does the Markdown conversion.

Then:

sanitize(...)

does the HTML security filtering.

3. Change your view

Currently you probably have:

<p><%= simple_format(message.content) %></p>

or:

<%= sanitize(message.content) %>

Change it to:

<div class="message-content">
<%= render_markdown(message.content) %>
</div>

Now your response:

A **Ruby block** is...
### Key Characteristics
* Not an object
* Can be passed to a method

will render approximately as:

A Ruby block is…

4. Important security point

Do not do this:

<%= raw(Commonmarker.to_html(message.content)) %>

without sanitization.

The LLM output is still untrusted input.

Keep:

sanitize(Commonmarker.to_html(text))

as your pipeline.

That’s a good senior-level AI security practice:

LLM output
↓
Markdown parser
↓
HTML
↓
Sanitizer
↓
Browser

What we’ve built so far

We’re no longer just experimenting with an API.

We now have:

                    Rails AI Assistant

Browser
   │
   ▼
Conversation UI
   │
   ▼
MessagesController
   │
   ▼
Ai::ChatService
   │
   ├── Conversation history
   │
   ▼
Ai::PromptBuilder
   │
   ▼
Ai::Client
   │
   ▼
OpenRouter
   │
   ▼
Free LLM
   │
   ▼
Message
   │
   ▼
PostgreSQL

That is already something we can discuss in a senior int.

Check our code in this repo: https://github.com/abhilashak/ai_assistant


Next: Step 9 – Streaming

We’ll now replace:

submit → wait → redirect

with:

submit
↓
Rails
↓
LLM streaming
↓
token-by-token response
↓
browser

We’ll use the Rails 8.1 stack appropriately and discuss SSE vs Turbo Streams vs Action Cable, rather than merely copying a ChatGPT-style implementation.

Happy AI Integration!

Integrate AI with Rails: AI bootcamp for Developers – Day 4 -Practical Course – Part 2

Now let’s move to the next step: make the Message model production-friendly.

We’ll start with the most important field: role.

Step 3 – Design Message.role

Currently our database allows:

role = anything

For example:

"user"
"assistant"
"system"
"foo"
"hello"
"something-invalid"

That’s not what we want.

Our AI application has a defined set of roles:

user
assistant
system

Later, when we introduce tool calling, we may also need to represent tool messages depending on the provider/API design. But for our current application, we’ll keep the persisted roles to these three.

Why use a string instead of an integer?

You may remember our previous discussion about Rails enums.

We could store:

0 = user
1 = assistant
2 = system

But for an AI application, I prefer a string-backed enum.

Database:

role
---------
user
assistant
system

instead of:

role
---------
0
1
2

Why?

1. Database is self-describing

When you run:

SELECT role FROM messages;

you immediately see:

user
assistant
assistant
user
system

2. Easier debugging

When you’re debugging an AI conversation, the actual value is obvious.

3. Safer for external APIs

LLM APIs already use strings such as:

{
"role": "user"
}

So our database representation matches the domain.

Step 3A – Add the Rails enum

Open:

app/models/message.rb

Currently you should have something like:

class Message < ApplicationRecord
belongs_to :conversation
end

Change it to:

class Message < ApplicationRecord
belongs_to :conversation
enum :role, {
user: "user",
assistant: "assistant",
system: "system"
}, validate: true
end

Understand this carefully

This:

enum :role, {
user: "user",
assistant: "assistant",
system: "system"
}, validate: true

doesn’t mean PostgreSQL has an enum type. We’re using a Rails enum backed by a string column.

PostgreSQL still has:

role character varying

Rails gives us a domain API on top of it.

Step 3B – Test the enum

Start Rails console:

bin/rails console

Find our message:

message = Message.first

Check:

message.role

You should get:

"user"

Now:

message.user?

Expected:

true

And:

message.assistant?

Expected:

false

Step 3C – Test the scopes

Rails also gives us useful scopes.

Try:

Message.user

and:

Message.assistant

and:

Message.system

For example:

Message.user

roughly translates to:

SELECT *
FROM messages
WHERE role = 'user';

This is one of the benefits of using an enum.

Step 3D – Test invalid values

Now try:

Message.new(
conversation: Conversation.first,
role: "something_else",
content: "test"
)

Because we specified:

validate: true

Rails should treat the role as invalid.

Check:

message = Message.new(
conversation: Conversation.first,
role: "something_else",
content: "test"
)
message.valid?

Expected:

false

Then:

message.errors.full_messages

You should see an error indicating that the role is not included in the allowed values.

Why validate: true?

This is worth understanding: Without validation, Rails enum behavior can raise an ArgumentError when assigning an invalid value.

With:

validate: true

we get normal ActiveRecord validation behavior:

message.valid?
→ false

and:

message.errors

contains the validation error.

That’s generally more convenient when the model is receiving user/application input.

Step 3E – One more important layer: Database constraint

There is a subtle issue here.

Rails validation protects you when data enters through Rails.

But PostgreSQL doesn’t know that only these values are valid:

user
assistant
system

Someone could execute:

INSERT INTO messages (conversation_id, role, content)
VALUES (1, 'invalid', '...');

directly against PostgreSQL.

The database would currently allow it.

This leads to an important senior-engineering principle:

Application-level validation and database-level integrity are complementary.

We’ll add a database constraint.

But don’t do that yet. First make sure the Rails enum works.

After that, we’re finally ready for the exciting part:

Rails
↓
Ai::Client
↓
LLM API
↓
Real AI response

Now let’s strengthen the model at the database level.

You currently have Rails validation:

enum :role, {
user: "user",
assistant: "assistant",
system: "system"
}, validate: true

That’s good, but a senior Rails application shouldn’t rely only on model validation for important data integrity.

Step 4 – Add Database Constraints

We want PostgreSQL itself to enforce:

role MUST be:
user
assistant
system

and:

content MUST NOT be NULL
role MUST NOT be NULL

This gives us two layers:

Rails
↓
Model validation
PostgreSQL
↓
Database constraint

4.1 Why NULL matters

Currently this is possible at the database level:

role = NULL

But an AI message without a role doesn’t make sense.

Likewise:

content = NULL

doesn’t represent a meaningful message.

So we’ll make both required.

4.2 Create a new migration

Don’t modify the old migration because it has already been executed and committed.

Generate a new migration:

bin/rails generate migration AddMessageConstraints

Rails should create:

db/migrate/XXXXXXXXXXXXXX_add_message_constraints.rb

Open that file.

4.3 Add NOT NULL constraints

Put this inside change:

class AddMessageConstraints < ActiveRecord::Migration[8.1]
def change
change_column_null :messages, :role, false
change_column_null :messages, :content, false
end
end

So conceptually:

def change
change_column_null :messages, :role, false
change_column_null :messages, :content, false
end

4.4 Add PostgreSQL CHECK constraint

Now we want PostgreSQL to enforce:

role IN ('user', 'assistant', 'system')

Add:

add_check_constraint(
:messages,
"role IN ('user', 'assistant', 'system')",
name: "messages_role_check"
)

Our migration becomes:

class AddMessageConstraints < ActiveRecord::Migration[8.1]
def change
change_column_null :messages, :role, false
change_column_null :messages, :content, false
add_check_constraint(
:messages,
"role IN ('user', 'assistant', 'system')",
name: "messages_role_check"
)
end
end

4.5 Run the migration

Execute:

bin/rails db:migrate

You should see Rails successfully applying the migration.

4.6 Inspect PostgreSQL

This is worth doing because understand what’s actually happening underneath Rails.

Run:

bin/rails dbconsole

Then:

\d messages

Look toward the bottom.

You should see a check constraint similar to:

messages_role_check
CHECK ((role)::text = ANY (...))

The exact display can vary by PostgreSQL version.

Also check:

\d+ messages

4.7 Test the database constraint

Now let’s prove that PostgreSQL protects us even if Rails is bypassed.

Inside psql, try:

INSERT INTO messages
(conversation_id, role, content, created_at, updated_at)
VALUES
(1, 'invalid', 'This should fail', NOW(), NOW());

You should get an error similar to:

ERROR: new row for relation "messages" violates check constraint "messages_role_check"

That’s exactly what we want.

The database is now protecting the data.

Why is this important?

Suppose an int. asks:

“Why do you have both Rails validation and a PostgreSQL constraint?”

A strong senior-level answer would be:

“Rails validations provide application-level feedback and are useful for normal model operations, but they’re not a database integrity guarantee because data can enter through other paths. For important invariants such as message roles, I also enforce the constraint at the PostgreSQL level.”

That’s a much stronger answer than:

“Because Rails has validations.”

4.8 One more design question: content

We’re making:

change_column_null :messages, :content, false

But should an AI message be allowed to contain an empty string?

For example:

content: ""

NOT NULL allows that.

So:

NULL NO
"" technically allowed
"Hello" YES

Whether empty content should be allowed is an application-level business rule.

We can later decide whether to add:

validates :content, presence: true

But don’t add that yet.

There are legitimate AI API situations where a message may not have ordinary text content – for example, tool-related or structured content. We’ll revisit our message representation when we implement tool calling.

4.9 Test a valid message

Exit psql:

\q

Then:

bin/rails c

Run:

conversation = Conversation.first

Then:

message = conversation.messages.create(
role: :user,
content: "What is Ruby?"
)

Check:

message.persisted?

You should get:

true

And:

message.role

should return:

"user"

Stop Here

Please do these in order:

bin/rails generate migration AddMessageConstraints

Edit the migration with the constraints above.

Then:

bin/rails db:migrate

Verify with:

bin/rails dbconsole
\d messages

Then test the invalid role directly in PostgreSQL.

Finally:

git add app/models/message.rb db/migrate
git commit -m "feat: validate message roles"
git push

NOW: “Message constraints are done.”

Then we move to the big milestone: Our First Real LLM API Call


Excellent. We now have a clean foundation:

Ruby 3.4.1
Rails 8.1
PostgreSQL
Conversation
│
└── Message
├── role
├── content
├── model
├── input_tokens
└── output_tokens
Ai::Client

Now we reach the first real AI step.

Step 5 – Make Our First LLM API Call

We’re going to do this in a deliberately controlled way.

Don’t build the Chat UI yet.

First, we need to understand:

Ruby
↓
Ai::Client
↓
HTTP request
↓
LLM provider
↓
HTTP response
↓
Ruby

Once we understand this, we’ll wrap it nicely into Rails architecture.

5.1 First decision – which provider?

For this practical course, let’s start with OpenAI.

Not because you must use OpenAI in production, but because it gives us a straightforward API to understand the fundamentals.

Later we’ll discuss:

Rails
│
├── OpenAI
├── Anthropic
└── Gemini

and how to design our Ai::Client so that we’re not tightly coupled to one provider.

5.2 Before writing code – understand the request

Conceptually, we’re going to send something like:

POST /v1/responses
{
"model": "...",
"input": "Explain Ruby blocks in simple terms."
}

The provider’s server processes the request:

Rails
│
│ HTTPS
▼
OpenAI API
│
▼
LLM
│
▼
Response

The important thing to understand is:

An LLM API is an HTTP API.

The Ruby SDK is just a convenient abstraction around HTTP.

5.3 Check our Ai::Client

You already created:

app/services/ai/client.rb

Open it.

If it currently contains nothing useful, that’s completely fine.

For now, make it:

# app/services/ai/client.rb

class Ai::Client
end

Don’t add API code yet.

5.4 Configure the API key securely

Do not put our API key in Ruby source code.

We have two common approaches:

Environment variables

or:

Rails encrypted credentials

For this project, I’m going to use Rails encrypted credentials because it’s a good opportunity to understand how Rails handles secrets.

5.5 Create Rails encrypted credentials

Run:

➜  ai_assistant git:(main) ✗ VISUAL="code --wait" rails credentials:edit

Rails will open our configured editor.

Add:

openai:
api_key: OUR_OPENAI_API_KEY

For example:

openai:
api_key: sk-xxxxxxxxxxxxxxxx

Use our actual API key locally, but never paste it into this conversation or commit it to GitHub.

Save and close the editor

What’s actually happening?

Rails creates/uses:

config/credentials.yml.enc

This file is encrypted.

Our encryption key is stored separately in:

config/master.key

The important rule is:

config/credentials.yml.enc
↓
COMMIT
↓
GitHub

is okay.

But:

config/master.key

should never be committed to GitHub.

Check:

git status

You should not see:

config/master.key

as a file to commit.

5.6 Verify Rails can read the key

Run:

bin/rails console

Then:

Rails.application.credentials.dig(:openai, :api_key)

You should get our key back, just verify that it returns a string rather than nil.

Then:

exit

5.7 Why use dig?

Our credentials structure is:

openai:
api_key: ...

which Rails exposes approximately as:

{
openai: {
api_key: "..."
}
}

So:

Rails.application.credentials.dig(:openai, :api_key)

means:

credentials
↓
openai
↓
api_key

This is cleaner than accessing nested values manually.

5.8 Now configure Ai::Client

Open:

app/services/ai/client.rb

Change it to:

class Ai::Client
def initialize
@api_key = Rails.application.credentials.dig(:openai, :api_key)
end
end

Now the client knows how to retrieve its secret.

5.9 Add a safety check

We don’t want the application to fail mysteriously later.

Add:

class Ai::Client
  def initialize
    @api_key = Rails.application.credentials.dig(:openai, :api_key)

    raise "OpenAI API key is missing" if @api_key.blank?
  end
end

Now:

Ai::Client.new

will fail immediately if the key isn’t configured. This is called fail-fast configuration.

5.10 Test the client

Run:

bin/rails console

Then:

client = Ai::Client.new

If everything is configured correctly, it should return:

#<Ai::Client:0x...>

No API request has happened yet.

We’re only testing:

Rails credentials
↓
Ai::Client

Check our code in this repo: https://github.com/abhilashak/ai_assistant


Stop Here

Don’t make the API request yet.

complete only these steps first:

1. Configure credentials

bin/rails credentials:edit

with:

openai:
api_key: OUR_KEY

2. Verify:

bin/rails console
Rails.application.credentials.dig(:openai, :api_key)

Don’t show me the key.

3. Update:

app/services/ai/client.rb

to:

class Ai::Client
def initialize
@api_key = Rails.application.credentials.dig(:openai, :api_key)
raise "OpenAI API key is missing" if @api_key.blank?
end
end

4. Test:

client = Ai::Client.new

Now: “Ai::Client credentials is done.”

Next topic: Step 5.11: install/configure the OpenAI Ruby client and make the first actual LLM request.

to be continued ..

Learn AI with Rails: AI Bootcamp for Developers – RAG, Embeddings & Vector Databases – Day 3

RAG is one of the first things we’d understand. Most AI products are not just “ChatGPT wrappers.” They become valuable because they answer questions about company-specific data.

Examples:

  • Internal documentation
  • HR policies
  • Product manuals
  • Customer support articles
  • Legal contracts
  • Medical records
  • Source code
  • Jira tickets
  • Slack messages
  • GitHub repositories

ChatGPT doesn’t know these documents. That’s where RAG comes in.


Goal

By the end of today, you should confidently answer:

  • What is RAG?
  • Why do we need RAG?
  • What are embeddings?
  • Why can’t we just send an entire PDF to the LLM?
  • What is semantic search?
  • What is a vector database?
  • Why is pgvector popular in Rails?
  • How would you build a document chat system?

Part 1 – Why LLMs Alone Are Not Enough

Imagine you build an HR chatbot.

The user asks:

“How many annual leave days do employees receive?”

Your company’s HR policy says:

24 days.

But the LLM was trained months ago and has never seen your HR document.

Without access to your data, it has to guess—or say it doesn’t know.

This is the fundamental problem RAG solves.


Part 2 – What is RAG?

RAG = Retrieval-Augmented Generation

Break it down:

  • Retrieval → Find relevant information.
  • Augmented → Add that information to the prompt.
  • Generation → The LLM generates the final answer using that context.

The key idea:

The LLM isn’t expected to know everything—it is given the right information at request time.

High-Level Flow

User Question
│
▼
Retrieve Relevant Documents
│
▼
Add Documents to Prompt
│
▼
LLM Generates Answer
│
▼
User

Notice that the LLM doesn’t search your database directly.

Your Rails application retrieves the data first.

Int. Question

What is RAG?

A strong answer:

Retrieval-Augmented Generation is a technique where relevant external information is retrieved first and then supplied to the language model as context, allowing it to answer questions using current or private data.


Part 3 – Why Not Paste the Entire PDF?

A common beginner idea is:

“I’ll upload the whole manual to ChatGPT.”

Let’s say your PDF is:

  • 800 pages
  • 350,000 words

Problems:

1. Context Window Limits

The entire document may not fit into the model’s context window.

2. Cost

More tokens = higher API cost.

3. Speed

Larger prompts take longer to process.

4. Noise

Most of the document is irrelevant to the user’s question.

If someone asks:

“How do I reset my password?”

Why send 800 pages?

You only need the page that explains password resets.


Part 4 – The RAG Pipeline

This is one of the most important diagrams to remember.

PDF
↓
Extract Text
↓
Split into Chunks
↓
Generate Embeddings
↓
Store in Vector Database
──────────────
User Question
↓
Generate Query Embedding
↓
Similarity Search
↓
Top Matching Chunks
↓
LLM
↓
Answer

Every production RAG system follows a variation of this flow.


Part 5 – What Are Chunks?

Large documents are split into smaller pieces.

Example:

Instead of:

Employee Handbook
(350 pages)

Split into:

Chunk 1
Company Introduction
---------------
Chunk 2
Leave Policy
---------------
Chunk 3
Medical Insurance
---------------
Chunk 4
Travel Policy

Now retrieval becomes efficient.

Why Not One Sentence Per Chunk?

Very small chunks:

  • lose context

Very large chunks:

  • increase cost
  • contain unrelated information

Chunk size is a trade-off.


Part 6 – What Are Embeddings?

This is the concept that many developers initially find abstract.

Think of an embedding as a numeric representation of meaning.

The model converts text into a list of numbers.

For example (illustrative only):

"Ruby on Rails"
↓
[0.12, -0.44, 0.91, ...]

Another phrase:

"Rails Framework"
↓
[0.13, -0.43, 0.90, ...]

Even though the wording is different, the vectors end up close together because they have similar meaning.

The exact numbers don’t matter—you just need to know that similar meanings produce similar vectors.

Think of a Map

Imagine a map.

Nearby cities are close.

Faraway cities are distant.

Embeddings work similarly.

Ruby
Rails
Sinatra
Python
Cooking
Football

Ruby and Rails are “near” each other.

Cooking is far away.

The model has learned semantic relationships.

Int. Question

What is an embedding?

Good answer:

An embedding is a numerical vector that represents the semantic meaning of text, allowing similar concepts to be located near each other in vector space.


Part 7 – Semantic Search

Traditional SQL search:

WHERE title LIKE '%Rails%'

This only matches literal text.

Suppose your document says:

Ruby web framework

The user searches:

Rails

A keyword search may miss it.

Semantic search compares meaning, not exact words.

Example:

Document:

Ruby web framework

Query:

Rails

Keyword search: ❌ No match (depending on the implementation)

Semantic search: ✅ High similarity because the concepts are closely related.

Rails Analogy

Traditional search:

LIKE
ILIKE

Semantic search:

Embedding
↓
Vector Similarity
↓
Closest Meaning

That’s the major difference.


Part 8 – Vector Databases

Where do we store embeddings?

Inside a vector database.

Popular options:

  • pgvector (PostgreSQL extension)
  • Pinecone
  • Qdrant
  • Weaviate
  • Milvus

Why pgvector Is Popular in Rails

Because many Rails applications already use PostgreSQL.

Instead of introducing another database, you can extend PostgreSQL with vector support.

Benefits:

  • One database
  • Familiar tooling
  • ActiveRecord support
  • Simpler backups
  • Easier deployment

For many Rails applications, pgvector is an excellent first choice.

How Similarity Search Works

Suppose the user asks:

Password reset

The query becomes an embedding.

The database compares it with stored document embeddings.

Password Policy
0.98
-----------
Leave Policy
0.31
-----------
Travel Policy
0.22
-----------
Insurance
0.12

The most similar chunks are returned.

Those chunks are added to the prompt.


Part 9 – Complete Rails Architecture

A production Rails application might look like this:

Browser
↓
Rails Controller
↓
Question Service
↓
Embedding API
↓
pgvector Search
↓
Top 5 Chunks
↓
Prompt Builder
↓
LLM API
↓
Answer
↓
Store Conversation
↓
Browser

Notice that Rails coordinates every step.

The LLM is only responsible for generating the final answer.


Part 10 – RAG vs Fine-Tuning

A very common interview question.

RAG

  • External knowledge
  • Easy to update
  • Great for company documents
  • No model retraining

Fine-Tuning

  • Changes model behaviour
  • Expensive
  • Longer process
  • Better for specialised tasks or consistent output style

Rule of thumb:

If the knowledge changes frequently (documentation, policies, support articles), use RAG.


Part 11 – Example: Company Wiki Chatbot

Suppose your company has:

  • 2,000 documentation pages

The user asks:

“How do I deploy staging?”

Flow:

User
↓
Embedding
↓
Vector Search
↓
Deployment Guide
↓
LLM
↓
Answer

The LLM answers using your company’s deployment guide rather than guessing.


Part 12 – Where Does Sidekiq Fit?

Another practical interview topic.

Generating embeddings for thousands of documents can take time.

A common approach:

PDF Uploaded
↓
Active Job / Sidekiq
↓
Extract Text
↓
Split Chunks
↓
Generate Embeddings
↓
Store in pgvector

Keep the upload request fast and process indexing asynchronously.


Part 13 – Common RAG Mistakes

Sending Entire Documents: Slow and expensive.

Tiny Chunks: Not enough context.

Huge Chunks: Too much irrelevant information.

Never Updating Embeddings: If documents change, regenerate the affected embeddings.

Blind Trust: Retrieved text can also be outdated or incorrect.

Validate your data sources and refresh them when needed.

Imp. Questions

Practice answering these.

Fundamentals

  1. What is RAG?
  2. Why do we need RAG?
  3. Why can’t ChatGPT answer company-specific questions by default?
  4. Why not send an entire PDF?

Embeddings

  1. What is an embedding?
  2. Why are embeddings useful?
  3. What is semantic search?

Databases

  1. What is a vector database?
  2. Why use pgvector?
  3. How does similarity search work?

Rails

  1. Where would Sidekiq fit?
  2. How would you build a document chatbot?
  3. Would you store conversations?
  4. How would you update embeddings when documents change?

Practical Exercise 1

Think about a support portal.

The documents include:

  • Refund policy
  • Shipping policy
  • Returns
  • Coupons
  • Warranty

Now answer:

“My order arrived damaged.”

Which document(s) should your RAG system retrieve before asking the LLM to generate a response?

Explain why.


Practical Exercise 2

Design the Rails models for a document chat system.

For example, think about models such as:

  • Document
  • DocumentChunk
  • Conversation
  • Message

What responsibilities should each have?


Practical Exercise 3

Sketch a background job flow.

When a user uploads a PDF:

  1. What happens immediately?
  2. What should Sidekiq handle?
  3. When are embeddings created?
  4. When are they stored?
  5. What happens if embedding generation fails?

Think in terms of a production-ready system rather than just happy-path code.


Homework

  1. Draw the complete RAG pipeline from memory.
  2. Explain embeddings in your own words without using AI jargon.
  3. Explain semantic search versus keyword search.
  4. Explain why pgvector is a good fit for many Rails applications.
  5. Describe how Sidekiq helps during document ingestion.
  6. Answer all 14 interview questions aloud.

Int. Challenge

Imagine you’re asked this in an interview:

“We have a Rails application with 500,000 product manuals. Users should be able to ask questions about any manual. Design the system.”

A strong answer would include:

  • Rails as the orchestration layer
  • Background jobs for document ingestion
  • Chunking strategy
  • Embedding generation
  • pgvector (or another vector database)
  • Similarity search
  • Prompt construction
  • LLM generation
  • Conversation storage
  • Caching and monitoring
  • Security and access control (users should only retrieve documents they are authorized to access)

This kind of end-to-end system design discussion is what distinguishes a senior engineer from someone who has only experimented with AI APIs.


Day 4 Preview

Tomorrow we move from concepts to implementation:

Building AI Features in Ruby on Rails

We’ll cover:

  • AI architecture in Rails
  • Choosing Ruby AI libraries and SDKs
  • Service objects for AI integration
  • Streaming AI responses
  • Background jobs with Sidekiq
  • Conversation storage
  • Cost optimization
  • Error handling
  • Designing a production-ready AI service layer
  • A complete Rails AI project structure suitable for real-world applications

From Day 4 onward, the bootcamp becomes much more code-focused and closely aligned with the kinds of AI features senior Rails developers build in production.


Happy AI Learning! 🚀

Fixing PostgreSQL Startup Issues on macOS (Homebrew): A Real-World Troubleshooting Guide

Introduction

Recently, I encountered an interesting PostgreSQL issue on my MacBook.

PostgreSQL was installed via Homebrew and worked perfectly on one macOS user account. However, when switching to another account on the same machine, I was unable to connect to PostgreSQL using psql.

The error looked like this:

psql postgres
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed:
No such file or directory
Is the server running locally and accepting connections on that socket?

This article walks through the investigation, root cause analysis, and final solution.


Understanding the Error

When PostgreSQL starts successfully, it creates a Unix socket file:

/tmp/.s.PGSQL.5432

The psql client uses this socket by default to connect to the local PostgreSQL server.

The error indicates one of two possibilities:

  1. PostgreSQL is not running.
  2. PostgreSQL is running but not listening on the expected socket.

In my case, PostgreSQL was simply not running for the current macOS user account.


Initial Verification

Verify PostgreSQL Client Installation

which psql

Output:

/opt/homebrew/bin/psql

Check version:

psql --version

Output:

psql (PostgreSQL) 14.17 (Homebrew)

This confirmed that PostgreSQL client tools were correctly installed.

Verify Installed PostgreSQL Version

brew list | grep postgres

Output:

postgresql@14

Check Whether PostgreSQL Is Running

pg_isready

Output:

/tmp:5432 - no response

This confirmed that PostgreSQL was not accepting connections.

Manual Startup Worked

Interestingly, PostgreSQL could be started manually:

/opt/homebrew/opt/postgresql@14/bin/pg_ctl \
-D /opt/homebrew/var/postgresql@14 \
-l /opt/homebrew/var/log/postgresql.log start

Output:

waiting for server to start.... done
server started

This was a critical clue.

It told us:

  • PostgreSQL binaries were healthy.
  • Database files were healthy.
  • Data directory was healthy.
  • The issue was likely related to Homebrew services or macOS LaunchAgents.

Investigating Homebrew Services

Checking service status:

brew services list

Output:

Name Status User
postgresql@14 error 78 abhilash

Attempting to start the service:

brew services start postgresql@14

Result:

Bootstrap failed: 5: Input/output error
launchctl bootstrap gui/501

This indicated a problem with the macOS LaunchAgent used by Homebrew.


Root Cause

Homebrew services rely on macOS launchctl.

Each macOS user account gets its own LaunchAgents configuration.

Although PostgreSQL was installed globally under Homebrew, the LaunchAgent configuration for this specific user account had become corrupted or stale.

As a result:

  • Manual startup worked.
  • Automatic startup through Homebrew failed.

Fixing the LaunchAgent

Stop Existing Service

brew services stop postgresql@14

Remove Existing LaunchAgent

rm ~/Library/LaunchAgents/homebrew.mxcl.postgresql@14.plist

Clean Up Homebrew Services

brew services cleanup

Verify Ownership

ls -ld /opt/homebrew/var/postgresql@14

If ownership is incorrect:

sudo chown -R $(whoami):staff /opt/homebrew/var/postgresql@14

Recreate the Service

After cleanup:

brew services start postgresql@14

Output:

Successfully started `postgresql@14`

Checking status:

brew services list

Output:

postgresql@14 started

Success!


Verifying PostgreSQL Is Running

pg_isready

Output:

/tmp:5432 - accepting connections

Connecting:

psql postgres

Output:

postgres=#

PostgreSQL was now functioning normally.


Understanding a New Error

While reviewing PostgreSQL logs, I noticed:

FATAL: database "abhilash" does not exist

At first glance, this looked concerning.

However, this is normal behavior.

When you run:

psql

PostgreSQL automatically tries to connect to a database matching your operating system username.

For example:

macOS username = abhilash

PostgreSQL attempts:

CONNECT TO abhilash;

Since that database didn’t exist, PostgreSQL logged:

FATAL: database "abhilash" does not exist

Creating a Personal Database

To make plain psql work:

CREATE DATABASE abhilash;

Now simply running:

psql

works because PostgreSQL can find a matching database.


Key Lessons Learned

1. Verify Whether PostgreSQL Is Actually Running

pg_isready

is often the fastest diagnostic tool.

2. Manual Startup Helps Isolate the Problem

If pg_ctl start works, your PostgreSQL installation and data files are probably fine.

3. Homebrew Services Depend on macOS LaunchAgents

A corrupted LaunchAgent can prevent PostgreSQL from auto-starting even when PostgreSQL itself is healthy.

4. Don’t Reinstall Immediately

Many developers jump directly to:

brew uninstall postgresql
brew install postgresql

In this case, reinstalling would not have fixed the issue and could have introduced additional problems.

5. Read the PostgreSQL Logs

Logs quickly reveal whether you’re dealing with:

  • Permission issues
  • Missing databases
  • Port conflicts
  • Startup failures
  • Authentication errors

Final Verification Checklist

brew services list
pg_isready
psql postgres

Expected results:

postgresql@14 started
/tmp:5432 - accepting connections
postgres=#

At this point, PostgreSQL is healthy and configured to start automatically after reboot.


Conclusion

What initially appeared to be a PostgreSQL installation problem turned out to be a macOS LaunchAgent issue specific to one user account.

By methodically checking:

  • PostgreSQL installation
  • Server status
  • Homebrew services
  • LaunchAgent configuration
  • PostgreSQL logs

we were able to restore automatic startup without reinstalling PostgreSQL or risking data loss.

This experience serves as a reminder that startup problems are often service-management issues rather than database issues.

Happy Debugging! 🚀

GCP Cloud SQL Disaster Recovery: A Practical Guide for Developers

When a production database goes down – whether from a bad migration, an accidental DROP TABLE, or a rogue script – the clock starts ticking. Every minute of downtime is lost revenue, broken trust, and a very stressful Slack channel.

This post walks through how Google Cloud SQL’s backup and recovery features work, common disaster scenarios, and the recovery playbook a developer should follow for each. The examples use a typical SaaS application backed by PostgreSQL on Cloud SQL, but the principles apply broadly.

Cloud SQL Backup Fundamentals

Before anything goes wrong, you need to understand what Cloud SQL gives you out of the box and what you need to configure yourself.

Automated Backups

Cloud SQL can take daily automated backups of your instance. These are full snapshots of the entire database and are retained for a configurable window (default 7 days, max 365).

# gcloud: verify automated backups are enabled
gcloud sql instances describe my-instance \
  --format="value(settings.backupConfiguration)"

Key settings to configure:

SettingRecommendationWhy
backupConfiguration.enabledtrueNon-negotiable for production
backupConfiguration.startTimeOff-peak hours (e.g. 04:00 UTC)Minimizes performance impact
backupConfiguration.backupRetentionSettings.retainedBackups14-30Gives you a wider recovery window
backupConfiguration.pointInTimeRecoveryEnabledtrueEnables PITR (see below)
backupConfiguration.transactionLogRetentionDays7How far back PITR can reach

Point-in-Time Recovery (PITR)

Automated backups give you daily snapshots. PITR fills the gaps by continuously archiving write-ahead logs (WAL for PostgreSQL, binary logs for MySQL). This lets you restore to any second within the retention window — not just to the time of the last backup.

# Enable PITR on an existing instance
gcloud sql instances patch my-instance \
  --enable-point-in-time-recovery \
  --retained-transaction-log-days=7

PITR is the single most important setting for disaster recovery. Without it, you lose every write between your last automated backup and the incident.

On-Demand Backups

You can trigger a backup manually before risky operations:

gcloud sql backups create --instance=my-instance \
  --description="pre-migration-backup-2026-04-08"

Rule of thumb: always take an on-demand backup before running migrations, bulk data operations, or any ad-hoc SQL against production.


Disaster Scenarios and Recovery Playbooks

Scenario 1: Accidental Table Drop or Data Deletion

What happened: A developer ran a DROP TABLE or DELETE FROM without a WHERE clause against production. Maybe it was a script meant for staging. Maybe an AI-generated SQL statement was executed without review.

Impact: One or more tables are gone or empty. The application is throwing 500s.

Recovery options:

Option A: PITR (best if available)

Restore to the moment just before the destructive command. You’ll need the approximate timestamp.

# Restore to a clone instance first — never restore directly over production
gcloud sql instances clone my-instance my-instance-recovery \
  --point-in-time="2026-04-08T10:59:00Z"

This creates a new instance with the database state at that exact second. You can then:

  1. Verify the data on the clone
  2. Export the affected tables from the clone
  3. Import them back into the production instance
# Export a specific table from the recovery clone
gcloud sql export sql my-instance-recovery gs://my-bucket/recovery/users-table.sql \
  --database=myapp_production \
  --table=users

# Import into production
gcloud sql import sql my-instance gs://my-bucket/recovery/users-table.sql \
  --database=myapp_production

Option B: Restore from automated backup

If PITR is not enabled, restore the most recent automated backup that predates the incident.

# List available backups
gcloud sql backups list --instance=my-instance

# Restore a specific backup (this overwrites the instance)
gcloud sql backups restore BACKUP_ID --restore-instance=my-instance

Warning: Restoring a backup directly onto your production instance overwrites everything. All writes since that backup are lost. Prefer cloning to a recovery instance first.

The data gap problem:

When you restore from a backup taken at, say, 4:00 AM, but the incident happened at 11:00 AM, you lose 7 hours of data. This is the gap you’ll need to address manually. Common strategies:

  • Application-level event logs: If your app publishes events to a message queue (Kafka, Pub/Sub), you can replay them.
  • Analytics replicas: If you replicate data to BigQuery, Snowflake, or another analytics store, you can query the missing records from there and re-import them.
  • Audit tables: If your application logs changes to an audit table in a separate database, those records survive.
-- Example: querying BigQuery for records created during the gap window
SELECT *
FROM `project.dataset.user_actions`
WHERE created_at BETWEEN TIMESTAMP('2026-04-08 04:00:00', 'America/Vancouver')
  AND TIMESTAMP('2026-04-08 11:00:00', 'America/Vancouver')
  AND action_type = 'account_status_change'

You then re-ingest these records into production, typically via a script run in your application’s console or through a migration task.


Scenario 2: Interrupted Background Job

What happened: A critical scheduled job — say, one that generates weekly records for all active users — was running when the incident occurred. The database was restored from backup, but the job was killed mid-execution. Some users got their records; others didn’t.

Impact: No application errors (the data that exists is valid), but there’s a silent gap. Some users are missing records they should have.

Recovery playbook:

Step 1 — Quantify the gap

Before doing anything, measure what’s missing:

# Find users who should have a record but don't
target_date = Date.parse('2026-05-30')
users_missing = User.where(status: ['active', 'subscribed'])
  .where.not(id: WeeklyRecord.where(week_date: target_date).select(:user_id))
users_missing.count

Record the count. You’ll need it for verification later.

Step 2 – Understand the generation logic

Before re-running anything, understand what the job does:

  • Does it check for existing records before creating? (idempotent?)
  • Does it behave differently based on user status? (e.g., suspended users get a different treatment)
  • Does it trigger side effects? (emails, webhooks, billing)

If the job is idempotent — meaning running it twice for the same user produces the same result without duplicates — you can safely re-run it for all users, not just the ones missing records. This is simpler and safer than trying to target only the gap.

Step 3 – Re-run with guardrails

Write a targeted script rather than re-triggering the entire job:

target_date = Date.parse('2026-05-30')
# Pre-check
baseline_count = WeeklyRecord.where(week_date: target_date).count
puts "Records before: #{baseline_count}"
# Find and process missing users
users_missing = User.where(status: ['active', 'subscribed'])
.where.not(id: WeeklyRecord.where(week_date: target_date).select(:user_id))
puts "Users missing records: #{users_missing.count}"
users_missing.find_each do |user|
WeeklyRecordGenerator.new(user).generate(target_date)
rescue => e
puts "Failed for User ##{user.id}: #{e.message}"
end
# Post-check
new_count = WeeklyRecord.where(week_date: target_date).count
puts "Records after: #{new_count}"
puts "Delta: #{new_count - baseline_count}"

Step 4 – Verify

Check that:

  • The record count increased by the expected amount
  • No duplicates were created
  • No users are still missing records
  • Any status-dependent logic was applied correctly (e.g., suspended users got the right treatment)

Scenario 3: Corrupted Data from a Bad Migration

What happened: A migration altered a column type, dropped a constraint, or backfilled data incorrectly. The application is running but producing wrong results.

Impact: Data is present but incorrect. This is often harder to detect than missing data.

Recovery playbook:

  1. Don’t panic-restore. If the app is functional (just producing wrong data), you have time to assess.
  2. Clone to a recovery instance from a backup predating the migration: gcloud sql instances clone my-instance pre-migration-clone \ --point-in-time="2026-04-07T23:00:00Z"
  3. Diff the data between production and the clone to understand exactly what changed: -- Compare row counts SELECT 'production' as source, count(*) FROM production.orders UNION ALL SELECT 'backup' as source, count(*) FROM backup_clone.orders; -- Find rows that differ SELECT p.id, p.amount as prod_amount, b.amount as backup_amount FROM production.orders p JOIN backup_clone.orders b ON p.id = b.id WHERE p.amount != b.amount;
  4. Write a targeted fix rather than a full restore (which would lose post-migration legitimate writes).
  5. Write a rollback migration if the schema change itself was the problem.

Scenario 4: Full Instance Failure

What happened: The Cloud SQL instance is unreachable – maybe a zone outage, maybe accidental instance deletion.

Recovery options:

If the instance still exists (zone outage):

Cloud SQL instances configured for high availability will automatically failover to a standby in another zone. If you don’t have HA enabled:

# Enable HA (requires instance restart)
gcloud sql instances patch my-instance --availability-type=REGIONAL

If the instance was deleted:

Deleted instances can be recovered within a limited window if deletion protection wasn’t bypassed:

# Enable deletion protection
gcloud sql instances patch my-instance --deletion-protection

If truly gone, restore from the most recent backup to a new instance:

gcloud sql instances create my-instance-restored \
--source-backup=BACKUP_ID \
--tier=db-custom-4-16384 \
--region=us-west1

Then update your application’s database connection string to point to the new instance.


Prevention Checklist

The best disaster recovery is the one you never need. Here’s what to set up before things go wrong:

Cloud SQL Configuration

# The production-ready configuration checklist
gcloud sql instances patch my-instance \
--backup-start-time=04:00 \
--enable-point-in-time-recovery \
--retained-transaction-log-days=7 \
--retained-backups-count=30 \
--deletion-protection \
--availability-type=REGIONAL

Operational Practices

1. Never run ad-hoc SQL directly against production

Use a read replica for investigative queries. If you must write, use a transaction with a manual ROLLBACK checkpoint:

BEGIN;

-- Your change here
UPDATE users SET status = 'inactive' WHERE last_login < '2025-01-01';

-- Verify before committing
SELECT count(*) FROM users WHERE status = 'inactive';

-- Only if the count looks right:
COMMIT;
-- Otherwise:
ROLLBACK;

2. Take on-demand backups before risky operations

gcloud sql backups create --instance=my-instance \
--description="pre-bulk-update-$(date +%Y%m%d-%H%M%S)"

3. Review AI-generated SQL before executing

AI tools are excellent at generating SQL, but they don’t understand your data invariants. A syntactically correct DROP TABLE or DELETE without a WHERE clause is still catastrophic. Always:

  • Read the generated SQL line by line
  • Run it on staging first
  • Wrap destructive operations in a transaction
  • Have a second pair of eyes for DDL changes

4. Maintain an analytics replica

Replicate critical tables to BigQuery or another analytics store. This serves as both an analytics platform and a recovery source. If your primary database loses data, you can query the replica for the gap window and re-ingest.

# Set up a BigQuery data transfer from Cloud SQL
bq mk --transfer_config \
--target_dataset=sql_replica \
--display_name="Production SQL Replica" \
--data_source=scheduled_query \
--schedule="every 1 hours"

5. Use IAM to restrict destructive operations

Not every developer needs cloudsql.instances.delete or direct SQL access to production:

# Create a read-only role for most developers
gcloud projects add-iam-policy-binding my-project \
--member="group:developers@company.com" \
--role="roles/cloudsql.viewer"
# Grant write access only to the ops team
gcloud projects add-iam-policy-binding my-project \
--member="group:database-ops@company.com" \
--role="roles/cloudsql.admin"

The Recovery Timeline: What Happens in Practice

Here’s what a real recovery typically looks like, end to end:

T+0min Incident detected (alerts fire, app errors spike)
T+5min Confirm the issue — is it a code bug or data loss?
T+10min Identify the last good backup / PITR target
T+15min Clone instance from backup (takes 5-30 min depending on size)
T+45min Verify restored data on the clone
T+60min Restore production from clone or selectively import tables
T+90min Identify the data gap (writes between backup and incident)
T+120min Query analytics replica / event logs for gap data
T+150min Re-ingest gap data, verify counts
T+180min Re-run interrupted jobs with verification
T+210min Final validation — all counts match, no duplicates, app healthy
T+240min Post-incident review

The total time depends on database size, gap complexity, and whether you had PITR enabled. With PITR, the gap is seconds. Without it, you could be looking at hours of manual data reconciliation.


Key Takeaways

  1. Enable PITR. It’s the difference between losing seconds of data and losing hours.
  2. Always clone to a recovery instance first. Never restore directly over production unless you have no other option.
  3. Maintain an analytics replica. It’s your insurance policy for the data gap.
  4. Quantify before you fix. Record counts before and after every recovery step. You can’t verify what you didn’t measure.
  5. Understand your jobs’ idempotency. If a background job was interrupted, knowing whether it’s safe to re-run is the difference between a smooth recovery and creating a bigger mess.
  6. Take on-demand backups before risky operations. The 30 seconds it takes could save you 4 hours of recovery.
  7. Review all SQL before execution. Especially AI-generated SQL. Trust, but verify.

Production incidents are stressful, but with the right configuration and a clear playbook, they don’t have to be catastrophic. Set up your backups today — future you will be grateful.

Happy fixing!