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
  • Validation, assignation
  • Migration
  1. Additional and advanced features

Enums

Clear offers support of PG enum.

To define an enum, use the Clear.enum method:

# Define the enum
Clear.enum Gender, "male", "female"

This will create a new record called MyApp::Gender, which contains the constants Male and Female.

Validation, assignation

You can use the new type directly in your model:

class User
  include Clear::Model
  #...

  column gender : Gender
end

Assignation cannot be made from string, but instead from constants:

u = User.new
u.gender = MyApp::Gender::Male

List of helpers are present for validation and conversion from/to string:

MyApp::Gender.authorized_values # < return ["male", "female"]
MyApp::Gender.all # < return [MyApp::Gender::Male, MyApp::Gender::Female]

MyApp::Gender::Female.to_s # Return "female"

MyApp::Gender.from_string("male") # < return MyApp::Gender::Male
MyApp::Gender.from_string("unknown") # < throw Clear::IllegalEnumValueError

MyApp::Gender.valid?("female") #< Return true
MyApp::Gender.valid?("unknown") #< Return false

Migration

class MyMigration1
    include Clear::Migration

    def change(dir)
        create_enum("gender", %w(male female))
    end
end
PreviousSymbol vs StringNextBCrypt

Last updated 6 years ago