module CQL::ActiveRecord::DirtyTracking

Overview

Opt-in change tracking. A record remembers its column values as last loaded or saved, reports what changed since, and update!/save send only the changed columns: a column another writer changed meanwhile is left alone, and a record with no changes sends no UPDATE (and keeps its updated_at). Callbacks still run.

Include it after CQL::ActiveRecord::Model:

class Profile
  include CQL::ActiveRecord::Model(Int64)
  include CQL::ActiveRecord::DirtyTracking
  db_context AcmeDB, :users

  property name : String = ""
  property updated_at : Time?

  def initialize
  end
end

profile = Profile.find_by!(name: "Ada")
profile.name = "Ada Lovelace"
profile.changes # => {:name => {"Ada", "Ada Lovelace"}}
profile.save    # UPDATE users SET name = ?, updated_at = ? WHERE users.id = ?

Changes are found by comparing values, so assignments through setters, attributes and instance variables all count. A record that was never loaded or saved counts every attribute as changed.

Defined in:

active_record/dirty_tracking.cr

Instance Method Summary

Instance Method Detail

def attribute_changed?(name : Symbol) : Bool #

[View source]
def changed? : Bool #

Whether any attribute differs from its last loaded or saved value.


[View source]
def changed_columns : Hash(Symbol, DB::Any) #

The changed columns and their new values, as an UPDATE sets them (never the primary key).


[View source]
def changes : Hash(Symbol, Tuple(DB::Any, DB::Any)) #

Each changed attribute with its {old, new} values (old is nil for a record never loaded or saved).


[View source]
def clear_changes! : Nil #

Takes the current values as the saved ones. Byte slices are copied, so changing one in place still counts as a change.


[View source]