Create Query Scopes

This guide shows you how to create reusable query scopes for common filtering patterns.

Define a Scope

Add class methods that return query builders:

struct Post
  include CQL::ActiveRecord::Model(Int64)
  db_context MyDB, :posts

  property id : Int64?
  property title : String
  property published : Bool = false
  property views_count : Int64 = 0
  property created_at : Time?

  # Scopes
  def self.published
    where(published: true)
  end

  def self.draft
    where(published: false)
  end

  def self.popular(min_views = 100)
    where { views_count >= min_views }
  end

  def self.recent(days = 7)
    where { created_at > days.days.ago }
  end
end

Use Scopes

Scope with Parameters

Conditional Scopes

Default Scope Pattern

Create a method for commonly used conditions:

Scope Chaining

Scopes can be chained in any order:

Scope with Ordering

Complex Scopes

Scopes work with relationships:

Verify Scopes Work

Last updated

Was this helpful?