Clear ORM
  • Welcome to Clear
  • Introduction
    • Setup
  • Model
    • Defining your model
      • Describing your columns
      • Primary Keys
      • Converters
    • Associations
      • belongs_to
      • has_many
      • has_many through
      • has_one
    • Lifecycle
      • Persistence
      • Validations
      • Triggers
    • Batchs operations
      • Bulk update
      • Bulk insert & delete
    • Transactions & Save Points
      • Transaction & Savepoints
      • Connection pool
    • Locks
  • Querying
    • The collection object
      • Filter the query
        • Filter the query – The Expression Engine
        • Find, First, Last, Offset, Limit
        • Aggregation
        • Ordering & Group by
      • Fetching the query
        • Each and Fetch
        • Cursored fetching
        • Model extra attributes
      • Joins
      • Eager Loading
      • Window and CTE
      • Scopes
    • Writing low-level SQL
      • Select Clause
      • Insert Clause
      • Delete Clause
  • Migrations
    • Manage migrations
    • Call migration script
    • Migration CLI
  • Additional and advanced features
    • JSONB
    • Symbol vs String
    • Enums
    • BCrypt
    • Full Text Search
    • Handling multi-connection
  • Other resources
    • API Documentation
    • Inline documentation
    • Github repository
    • Credits
    • Benchmark
Powered by GitBook
On this page
  1. Querying
  2. The collection object

Scopes

Scope provides elegant way to write commonly used query fragments and improve readability of your code. Scope returns a new collection Collection or taint the current Collection.

Let's get an example:

class User
    include Clear::Model

    primary_key

    column role : String
    column role_level : Int32
    column email : String
    column active : Bool

    scope :with_privileges do |level|
        where{ role.in?(%w(superadmin admin)) | (role_level > level) }
    end
    scope(:active){ where(active: true) }
end

# Later one:
User.with_privileges(3).each do |x|
    puts "Admin #{x.id} - #{x.email}"
end

Scope can be easily chained and you can pass argument to them too:

User.with_admin_privileges(4).active

Scope live both in Model::Collection and Model code space, meaning you may ignore Model.query to start a new Collection but instead go straight to Model.scope.

PreviousWindow and CTENextWriting low-level SQL

Last updated 6 years ago