Define a Model

This guide shows you how to define a CQL Active Record model that maps to a database table.

Basic Model Definition

To define a model, create a struct or class that includes the Active Record module:

struct User
  include CQL::ActiveRecord::Model(Int64)
  db_context MyDB, :users

  property id : Int64?
  property name : String
  property email : String
  property created_at : Time?
  property updated_at : Time?

  def initialize(@name : String, @email : String)
  end
end

Key Components

1. Include the Active Record Module

The type parameter specifies your primary key type: Int32, Int64, UUID, or String (for ULIDs).

2. Set the Database Context

This connects the model to a specific schema and table.

3. Define Properties

4. Create a Constructor

Primary Key Types

Integer (default)

UUID

ULID (for sortable IDs)

Excluding Fields from Persistence

Use the DB::Field annotation to exclude virtual fields:

Adding Custom Methods

Add business logic directly in your model:

Verify Your Model

Test that your model works:

Common Issues

"No database context defined": Ensure you called db_context with correct schema and table.

"Could not find column": Property names must match database column names.

"Type mismatch": Crystal property types must match database column types.

Last updated

Was this helpful?