Defining Models
CQL Active Record models are Crystal struct
s that map directly to database tables. Each model encapsulates the table's columns as properties, provides type-safe access to data, and includes methods for persistence, querying, and associations.
Basic Model Definition
To define a model:
Key points:
Use
struct
for models (Crystal convention for value types).include CQL::ActiveRecord::Model(PkType)
mixes in all Active Record features. The type parameter specifies the primary key type (e.g.,Int32
,Int64
,UUID
).db_context AcmeDB, :users
links the model to a specific table in a database context.Use
property
for each column. Nullable types (e.g.,Int32?
) are used for columns that may beNULL
or auto-generated.
Primary Keys
The primary key type is specified in the
Model
inclusion.By convention, the primary key property is named
id
.If the primary key is auto-generated, make it nullable (
id : Int32?
).
Working with Attributes
Individual Attribute Access
Use the generated getter and setter methods:
Accessing All Attributes as a Hash
Use the attributes
method to get a hash of all attribute values:
Mass Assignment
Set multiple attributes at once using a hash or keyword arguments:
Note: These methods only update the instance in memory. Call save
to persist changes.
Attribute Names
Get all attribute names as symbols:
Best Practices
Use
property
for all columns you want to map.Use nullable types for columns that may be
NULL
or auto-generated.Use mass assignment carefully, especially with user input.
Use direct property access for individual attributes; use
attributes
for bulk operations.
Example: Complete Model
For more on querying and persistence, see the other guides in this directory.
Last updated
Was this helpful?