Part 3: Models and Relationships
What You'll Learn
Prerequisites
Step 1: Create the User Model
# src/models/user.cr
struct User
include CQL::ActiveRecord::Model(Int64)
db_context BlogDB, :users
property id : Int64?
property username : String
property email : String
property first_name : String?
property last_name : String?
property active : Bool = true
property created_at : Time?
property updated_at : Time?
# Relationships
has_many :posts, Post, :user_id
has_many :comments, Comment, :user_id
def initialize(
@username : String,
@email : String,
@first_name : String? = nil,
@last_name : String? = nil,
@active : Bool = true
)
end
# Custom methods
def full_name : String
if first_name && last_name
"#{first_name} #{last_name}"
elsif first_name
first_name.not_nil!
else
username
end
end
def display_name : String
first_name || username
end
endStep 2: Create the Category Model
Step 3: Create the Post Model
Step 4: Create the Comment Model
Step 5: Update the Main File
Step 6: Test the Models
Understanding Relationships
belongs_to
has_many
Model Best Practices
Summary
Next Steps
Last updated
Was this helpful?