### Comprehensive Order State Machine Example Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Example showing multiple callback types and event transitions in a single model. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do after_transition :on => :process do |order| order.calculate_totals end after_transition :to => :completed do |order| order.send_completion_email end after_transition :after_commit => true do |order| NotifyCustomerJob.perform_later(order.id) end event :process do transition :pending => :processing end event :complete do transition :processing => :completed end end end order = Order.create order.process # Calls after_transition callbacks ``` -------------------------------- ### Deserialize usage examples Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Demonstrates deserialization behavior in both auto-indexed and passthrough modes. ```ruby # Conversion mode (states auto-indexed) class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # auto-mapped to integer 0 state :processing # auto-mapped to integer 1 state :completed # auto-mapped to integer 2 end end type = Order.type_for_attribute(:status) type.deserialize(0) # => "pending" type.deserialize(1) # => "processing" type.deserialize(nil) # => nil # Passthrough mode (all states have explicit values) class LegacyOrder < ApplicationRecord state_machine :status, initial: :pending do state :pending, value: 0 state :approved, value: 1 end end type = LegacyOrder.type_for_attribute(:status) type.deserialize(1) # => 1 (raw integer, passthrough mode) ``` -------------------------------- ### Practical Callback Execution Example Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Demonstrates the interleaved execution of state machine callbacks and ActiveRecord lifecycle hooks. ```ruby class Vehicle < ApplicationRecord state_machine do before_transition { puts "1. before_transition" } end before_save { puts "3. before_save" } after_save { puts "5. after_save" } validates :name, presence: true validate :custom_validation def custom_validation puts "2. custom_validation" end end vehicle = Vehicle.new vehicle.ignite # Output: # 1. before_transition # 2. custom_validation # 3. before_save # 5. after_save ``` -------------------------------- ### Serialize usage examples Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Demonstrates serialization of state names to integers, including explicit value mapping. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # serializes to 0 state :processing # serializes to 1 state :completed # serializes to 2 end end type = Order.type_for_attribute(:status) type.serialize("pending") # => 0 type.serialize(:processing) # => 1 type.serialize(nil) # => nil # With explicit values class LegacyOrder < ApplicationRecord state_machine :status, initial: :pending do state :pending, value: 10 state :approved, value: 20 end end type = LegacyOrder.type_for_attribute(:status) type.serialize("pending") # => 10 (explicit value) type.serialize("approved") # => 20 ``` -------------------------------- ### Implement after_transition with ActiveRecord Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Example showing immediate and deferred callbacks within an ActiveRecord model. ```ruby class Vehicle < ApplicationRecord state_machine do after_transition :on => :ignite, :after_commit => true do |vehicle| # This runs after the transaction commits, safe for enqueueing jobs EngineWarmupJob.perform_later(vehicle) end after_transition do |vehicle, transition| # Runs immediately, inside the transaction puts "State transitioned from #{transition.from} to #{transition.to}" end event :ignite do transition :parked => :idling end end end # Usage vehicle = Vehicle.create(state: 'parked') vehicle.ignite # Performs transition, deferred callback fires after commit ``` -------------------------------- ### Install State Machines Active Record Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Commands to add the gem to your project dependencies. ```ruby gem 'state_machines-activerecord' ``` ```bash $ bundle ``` ```bash $ gem install state_machines-activerecord ``` -------------------------------- ### Automatic enum initialization Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Example showing how enum integration is initialized during state machine definition. ```ruby # This is called automatically during state_machine initialization class Order < ApplicationRecord enum :status, { pending: 0, processing: 1 } state_machine :status do # initialize_enum_integration called here state :pending, :processing end end ``` -------------------------------- ### Cast usage examples Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Demonstrates casting various input types to state names based on defined mappings. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # integer 0 state :processing # integer 1 state :completed # integer 2 end end type = Order.type_for_attribute(:status) type.cast(:pending) # => "pending" type.cast("processing") # => "processing" type.cast(2) # => "completed" (found by integer mapping) type.cast(nil) # => nil type.cast("invalid") # => "invalid" (unmapped value) ``` -------------------------------- ### Define initial state Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Specifies the starting state for new records. ```ruby state_machine :status, initial: :pending do state :pending state :processing state :completed end ``` -------------------------------- ### Instantiate Integer Type Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Example of creating a new instance of the integer type using a state collection and an optional raw type. ```ruby states = machine.states raw_type = ActiveModel::Type::Integer.new type = StateMachines::Type::Integer.new(states, raw_type: raw_type) ``` -------------------------------- ### Implement state machine callbacks in a model Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md A complete example showing how to integrate state machine callbacks within an ActiveRecord model class. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition :parked => any do |vehicle| vehicle.put_on_seatbelt end before_transition do |vehicle, transition| vehicle.log_event("Transitioning from #{transition.from} to #{transition.to}") end event :ignite do transition :parked => :idling end end def put_on_seatbelt self.seatbelt_on = true end def log_event(message) puts message end end vehicle = Vehicle.create vehicle.ignite # Before callbacks run here ``` -------------------------------- ### Handling Transition Exceptions Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Example of a failed transition due to model validation errors when using the bang method. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do event :ignite do transition :parked => :idling end end validates :name, presence: true end vehicle = Vehicle.new vehicle.ignite! # Raises: StateMachines::InvalidTransition: Cannot transition state via :ignite from :parked (Reason(s): Name cannot be blank) ``` -------------------------------- ### Query states using scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Examples of using generated state scopes on an ActiveRecord model. ```ruby Vehicle.with_state(:parked) # => ActiveRecord::Relation Vehicle.with_state(nil) # => ActiveRecord::Relation (all records) Vehicle.without_state(:parked) # => ActiveRecord::Relation ``` -------------------------------- ### Check enum integration status Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Usage example for verifying if enum integration is enabled. ```ruby class Order < ApplicationRecord enum :status, { pending: 0, processing: 1 } state_machine :status do state :pending, :processing end end machine = Order.state_machine(:status) machine.enum_integrated? # => true ``` -------------------------------- ### Enum integration metadata structure Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Example of the hash returned by detect_enum_integration. ```ruby { enabled: true, prefix: true, suffix: false, scopes: true, enum_values: { "pending" => 0, "processing" => 1, ... }, original_enum_methods: ["pending?", "processing?", "pending!", ...], state_machine_methods: [] } ``` -------------------------------- ### Log failed transitions in ActiveRecord Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Example of using after_failure to log transition details and validation errors to a database table. ```ruby class TransitionLog < ApplicationRecord connects_to database: { writing: :primary, reading: :primary } end class Order < ApplicationRecord state_machine :status, initial: :pending do after_failure do |order, transition| TransitionLog.create( order_id: order.id, event: transition.trigger, from_state: transition.from, to_state: transition.to, reason: order.errors.full_messages.join(', ') ) end before_transition do |order| # This failure will trigger after_failure order.errors.add(:base, 'Inventory unavailable') false end event :process do transition :pending => :processing end end end order = Order.create order.process # => false, calls after_failure, logs to TransitionLog ``` -------------------------------- ### Integer Column Configuration Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Example of using an integer column for state storage, which enables automatic conversion between state names and integers. ```ruby class CreateOrders < ActiveRecord::Migration[6.0] def change create_table :orders do |t| t.integer :status, default: 0 # Integer column t.timestamps end end end class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # Stored as 0 state :processing # Stored as 1 state :completed # Stored as 2 end end order = Order.create! order.read_attribute_before_type_cast(:status) # => 0 (integer stored) order.status # => "pending" (converted) ``` -------------------------------- ### String Column Configuration Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Example of using a string column for state storage, where state names are stored directly without conversion. ```ruby class CreateOrders < ActiveRecord::Migration[6.0] def change create_table :orders do |t| t.string :status, default: 'pending' # String column t.timestamps end end end class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending state :processing state :completed end end order = Order.create! order.status # => "pending" (string stored directly) ``` -------------------------------- ### Define State Machine in Active Record Model Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Example of defining a state machine within an Active Record model using transitions, events, and state-specific validations. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition :parked => any - :parked, :do => :put_on_seatbelt after_transition any => :parked do |vehicle, transition| vehicle.seatbelt = 'off' end around_transition :benchmark event :ignite do transition :parked => :idling end state :first_gear, :second_gear do validates :seatbelt_on, presence: true end end def put_on_seatbelt ... end def benchmark ... yield ... end end ``` -------------------------------- ### Contribute to the project Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Standard git workflow commands for contributing to the repository. ```bash git checkout -b my-new-feature ``` ```bash git commit -am 'Add some feature' ``` ```bash git push origin my-new-feature ``` -------------------------------- ### Accessing Configuration Metadata Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Shows how to inspect the mapping and method generation details of an enum-integrated state machine. ```ruby machine = Order.state_machine(:status) # Check integration details machine.enum_mapping # => {"pending"=>0, "processing"=>1, "completed"=>2} machine.original_enum_methods # => ["pending?", "processing?", ...] machine.state_machine_methods # => ["status_pending?", "status_processing?", ...] ``` -------------------------------- ### Implement state machine callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Hooks into transition lifecycles using before_transition, after_transition, and after_failure callbacks. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition :parked => :idling do |vehicle| vehicle.put_on_seatbelt end after_transition :on => :ignite, :after_commit => true do |vehicle| EngineWarmupJob.perform_later(vehicle) end after_failure do |vehicle, transition| puts "Could not transition via #{transition.trigger}" end event :ignite do transition :parked => :idling end end def put_on_seatbelt self.seatbelt_on = true end end ``` -------------------------------- ### Callback Execution Order List Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md The sequence of operations during a state machine transition using the default :save action. ```text 1. save() called 2. begin transaction 3. before_transition callbacks 4. validate object 5. after_validation callbacks (AR) 6. before_save callbacks (AR) 7. before_create/before_update callbacks (AR) 8. create/update in database 9. after_create/after_update callbacks (AR) 10. after_save callbacks (AR) 11. after_transition callbacks 12. commit transaction 13. after_commit callbacks (AR) 14. after_transition callbacks with :after_commit => true ``` -------------------------------- ### Configure Callback Block Parameters Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Callbacks can accept either just the object or both the object and the transition object. ```ruby # Receives object and optional transition before_transition do |object| # Only object, no transition available here end before_transition do |object, transition| # Both object and transition end after_transition do |object, transition| # Both object and transition end after_failure do |object, transition| # Both object and transition end ``` -------------------------------- ### Configure after_transition callback Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Define standard or post-commit transition callbacks. ```ruby class Vehicle < ApplicationRecord state_machine do after_transition do |vehicle, transition| # Same transition object as before_transition end after_transition after_commit: true do |vehicle, transition| # Executed after database commit end end end ``` -------------------------------- ### Implementing Deferred Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Demonstrates mixing immediate and deferred callbacks within an ActiveRecord model. ```ruby class Vehicle < ApplicationRecord state_machine do # Immediate callback (runs inside transaction) after_transition do |vehicle| AuditLog.create(vehicle_id: vehicle.id, action: 'transitioned') end # Deferred callback (runs after transaction commits) after_transition :after_commit => true do |vehicle| EngineWarmupJob.perform_later(vehicle) end event :ignite do transition :parked => :idling end end end vehicle = Vehicle.create vehicle.ignite # 1. AuditLog.create runs and is rolled back if transaction fails # 2. Transaction commits # 3. EngineWarmupJob.perform_later enqueues (outside transaction) ``` -------------------------------- ### Implementing after_transition with :after_commit Support Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Internal implementation showing how the after_commit option defers callback execution until the database transaction completes. ```ruby def after_transition(*args, **options, &block) # Flag handling and deferred callback implementation flag = options[:after_commit] return super unless flag == true || flag == false return super unless flag # Defer execution until transaction commits deferred = Callback.new(:after, method_options, &block) super(**branch_options, bind_to_object: false) do |object, transition| object.class.current_transaction.after_commit do catch(:halt) { deferred.call(object, {}, transition) } rescue StandardError => e ActiveSupport.error_reporter.report(e, ...) end end end ``` -------------------------------- ### Defining Explicit Integer State Mappings Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Demonstrates how to assign specific integer values to states within a state machine definition. ```ruby class Order < ApplicationRecord state_machine :status do state :pending, value: 10 state :processing, value: 20 state :completed, value: 30 end end order = Order.create(status: :pending) order.read_attribute_before_type_cast(:status) # => 10 ``` -------------------------------- ### Access Generated State Machine Methods Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Demonstrates usage of the prefixed state machine methods and scopes generated to avoid conflicts. ```ruby # Predicate methods order.status_pending? # => true (state machine method) order.status_processing? # => false (state machine method) order.status_completed? # => false (state machine method) # Bang methods (for conflict resolution only) # These are placeholders and raise runtime errors order.status_processing! # => raises RuntimeError # Scope methods Order.status_pending # State machine scope Order.status_processing # State machine scope Order.not_status_pending # Negative state machine scope ``` -------------------------------- ### Implement multiple state machines Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Demonstrates using different attributes for multiple state machines on a single model. ```ruby class Document < ApplicationRecord # First machine uses 'status' attribute state_machine :status do state :draft state :published end # Second machine uses 'approval' attribute state_machine :approval do state :pending state :approved state :rejected end end doc = Document.new doc.status # => "draft" doc.approval # => "pending" ``` -------------------------------- ### Project File Structure Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Displays the directory layout of the state_machines-activerecord gem. ```text lib/ ├── state_machines-activerecord.rb # Entry point └── state_machines/integrations/ └── active_record.rb # Main integration (950 lines) └── active_record/ ├── version.rb # Version constant ├── locale.rb # I18n translations └── type/ └── integer.rb # Integer type converter ``` -------------------------------- ### Handle Failed Transitions Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Demonstrates checking for transition failure when no valid path exists from the current state. ```ruby vehicle = Vehicle.create(state: :idling) vehicle.ignite # => false (already idling, no transition from idling) vehicle.errors[:state] # => ["cannot transition via \"ignite\""] ``` -------------------------------- ### Use Transparent State Scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Demonstrates how state scopes return all records when nil is passed, useful for dynamic search filters. ```ruby Vehicle.with_state(nil) # Returns all vehicles Vehicle.with_state(params[:state]) # Returns all vehicles if params[:state] is nil Vehicle.where(color: 'red').with_state(nil) # Returns all red vehicles (chainable) ``` -------------------------------- ### Use :save action for persistence Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Demonstrates the default behavior where state transitions automatically trigger a save. ```ruby class Order < ApplicationRecord state_machine :status, action: :save, initial: :pending do event :process do transition pending: :processing end end end order = Order.create! order.process # Automatically calls save order.reload order.status # => "processing" (persisted) ``` -------------------------------- ### Configure after_failure callback Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Handle failed transition attempts. ```ruby class Vehicle < ApplicationRecord state_machine do after_failure do |vehicle, transition| # Transition attempted but failed puts "Failed to #{transition.trigger}" end end end ``` -------------------------------- ### Optimizing ActiveRecord State Machine Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Demonstrates avoiding N+1 queries and deferring expensive operations to background jobs using after_commit. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do # Bad: Multiple queries in callback after_transition do |order| order.items.each { |item| item.process } # N+1 query end # Good: Use eager loading after_transition do |order| order.reload # or use includes during load order.items.each { |item| item.process } end # Best: Defer to background job after_transition :after_commit => true do |order| ProcessOrderJob.perform_later(order.id) end end end ``` -------------------------------- ### Define initialize_enum_integration Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Method signature for initializing enum integration. ```ruby def initialize_enum_integration ``` -------------------------------- ### Define Callbacks with Method References Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Use symbols to reference instance methods for state machine callbacks instead of blocks. ```ruby class Vehicle < ApplicationRecord state_machine do before_transition :validate_preconditions after_transition :log_transition after_failure :log_failure end def validate_preconditions seatbelt_on && fuel_level > 0 end def log_transition puts "Transition successful" end def log_failure puts "Transition failed" end end ``` -------------------------------- ### Configure Database Defaults for State Machines Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Align database column defaults with the initial state of the state machine to ensure data consistency. ```ruby # Column default should match initial state create_table :orders do |t| t.integer :status, default: 0 # Matches initial: :pending (index 0) end class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # Index 0 end end ``` ```ruby create_table :orders do |t| t.integer :status, default: 10 # Matches explicit value end class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending, value: 10 # Explicit value matches default state :processing, value: 20 end end ``` -------------------------------- ### Define before_transition callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Various ways to define before_transition hooks, including event-specific, state-specific, and conditional triggers. ```ruby before_transition do |object, transition| # Custom logic here end before_transition :on => :ignite do |object| # Only on specific event end before_transition :parked => :idling do |object| # Only for specific state change end before_transition :if => :condition_met? do |object| # Conditional execution end ``` -------------------------------- ### Persisting State Changes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Demonstrates manual persistence versus automatic persistence triggered by state machine events. ```ruby vehicle = Vehicle.create vehicle.state = :idling vehicle.save # Persists to database # The transition also saves automatically vehicle = Vehicle.create vehicle.ignite # Calls save internally and persists ``` -------------------------------- ### Defining Auto-Indexed State Mappings Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Shows how state machines automatically map states to integer values based on their definition order. ```ruby class Order < ApplicationRecord state_machine :status do state :pending # Mapped to 0 (position 0) state :processing # Mapped to 1 (position 1) state :completed # Mapped to 2 (position 2) end end order = Order.create(status: :pending) order.read_attribute_before_type_cast(:status) # => 0 ``` -------------------------------- ### Define after_transition callback Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Method signature for defining transition callbacks. ```ruby def after_transition(*args, **options, &block) ``` -------------------------------- ### Defining State Machine Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Hooks for executing logic during the transition lifecycle, including support for deferred callbacks after database commits. ```ruby state_machine do before_transition { |obj, trans| ... } # Before transition after_transition { |obj, trans| ... } # After transition after_transition :after_commit => true {} # Deferred until commit after_failure { |obj, trans| ... } # On transition failure end ``` -------------------------------- ### after_transition Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Creates a callback that executes after a transition, with optional deferred execution until database commit. ```APIDOC ## after_transition(*args, **options, &block) ### Description Creates a callback that executes after a transition, with optional deferred execution until database commit. ### Parameters - **args** (Array) - Required - Transition requirements (state, event conditions) - **options** (Hash) - Optional - Configuration hash with optional :after_commit flag - **block** (Proc) - Required - Callback code to execute ### Options - **after_commit** (Boolean) - Optional - When true, defers callback until transaction commit; when false, executes immediately - **if** (Proc/Symbol) - Optional - Condition that must be true to execute the callback - **unless** (Proc/Symbol) - Optional - Condition that must be false to execute the callback - **do** (Symbol/String) - Optional - Method name to call instead of a block - **bind_to_object** (Boolean) - Optional - Whether to bind the callback to the object instance ### Return Value Returns the callback object. ``` -------------------------------- ### Callback Method Parameters Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Callback methods receive the object as the first argument, and optionally the transition object as the second argument. ```ruby class Vehicle < ApplicationRecord state_machine do before_transition :validate_and_log end def validate_and_log # If method takes 1 parameter, object is passed # If method takes 2 parameters, object and transition are passed end def validate_and_log # One parameter: the object # self.class.name => Vehicle end end ``` -------------------------------- ### Implement State Machine Debugging Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/errors.md Uses transition hooks to log attempts, successes, and failures. Requires an ActiveRecord model with the state_machine gem. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do before_transition do |order, transition| puts "Attempting: #{transition.from} → #{transition.to} via #{transition.trigger}" end after_transition do |order, transition| puts "Successfully transitioned to #{order.status}" end after_failure do |order, transition| puts "Failed to transition via #{transition.trigger}" puts "Errors: #{order.errors.full_messages.join(', ')}" end event :process do transition pending: :processing end end validates :customer_id, presence: true end # Test transitions order = Order.create(customer_id: nil) order.process # => false, prints failure messages # Output: # Attempting: pending → processing via process # Failed to transition via process # Errors: Customer can't be blank order.update(customer_id: 1) order.process # => true, prints success message # Output: # Attempting: pending → processing via process # Successfully transitioned to processing ``` -------------------------------- ### Manual Error Handling Pattern Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Recommended pattern for reporting errors within deferred callbacks. ```ruby class Vehicle < ApplicationRecord state_machine do after_transition :after_commit => true do |vehicle| begin perform_important_task(vehicle) rescue StandardError => e Rails.error.report(e, source: 'Vehicle#ignite') end end end end ``` -------------------------------- ### Automatic Persistence in ActiveRecord Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Demonstrates how state changes are automatically persisted to the database by default. ```ruby vehicle = Vehicle.create(state: :parked) vehicle.ignite # Calls save internally vehicle.reload vehicle.state # => "idling" (persisted) ``` -------------------------------- ### Define after_failure callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Basic syntax for defining global or event-specific after_failure callbacks. ```ruby after_failure do |object, transition| # Transition was allowed but failed end after_failure :on => :ignite do |object| # Only for specific event end ``` -------------------------------- ### Implement After Failure Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Uses after_failure callbacks to perform cleanup or auditing when a transition fails to save. ```ruby class TransitionLog < ApplicationRecord connects_to database: { writing: :primary, reading: :primary } end class Vehicle < ApplicationRecord state_machine do after_failure do |vehicle, transition| TransitionLog.create( vehicle_id: vehicle.id, transition: transition.inspect, errors: vehicle.errors.full_messages ) end event :ignite do transition :parked => :idling end end end ``` -------------------------------- ### Chainable ActiveRecord State Machine Scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/scopes.md Demonstrates chaining state-based scopes with standard ActiveRecord query methods like where, order, and limit. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do event :process do transition pending: :processing end event :complete do transition processing: :completed end end end # Complex queries Order.with_state(:pending, :processing) .where('created_at > ?', 1.week.ago) .where(user_id: [1, 2, 3]) .order(created_at: :desc) .limit(10) # Combining with and without Order.with_state(:pending) .where(payment_method: 'credit_card') .where.not(user_id: nil) # Count records in state Order.with_state(:completed).count # Batch operations on records in state Order.with_state(:pending).each { |order| order.process! } ``` -------------------------------- ### Eager loading with state scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/scopes.md Combine state scopes with includes to reduce N+1 query issues. ```ruby Order.with_state(:pending).includes(:user, :items).all ``` -------------------------------- ### Initialize Integer Type Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Constructor signature for the custom integer attribute type. ```ruby def initialize(states, raw_type: nil) ``` -------------------------------- ### Firing Events and Transitions Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Methods for triggering state transitions on an ActiveRecord model instance. ```ruby vehicle = Vehicle.create vehicle.ignite # Fire event, returns true/false vehicle.ignite! # Fire event, raises on failure vehicle.state_event = 'ignite' vehicle.save # Transitioning via event attribute ``` -------------------------------- ### Configure before_transition callback Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Access the Transition object within a before_transition block. ```ruby class Vehicle < ApplicationRecord state_machine do before_transition do |vehicle, transition| # transition is a Transition object puts transition.inspect end end end ``` -------------------------------- ### Configure persistence action Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Specifies the method called to persist state changes to the database. ```ruby state_machine :status, action: :save do ... end ``` -------------------------------- ### Defining and Using State Machine Events Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Full implementation of a state machine within an ActiveRecord model with basic transition usage. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do event :ignite do transition :parked => :idling end event :park do transition :idling => :parked end end end vehicle = Vehicle.create vehicle.state # => "parked" result = vehicle.ignite # => true vehicle.state # => "idling" vehicle.park # => true vehicle.state # => "parked" ``` -------------------------------- ### Enable transactions for atomicity Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Shows how transactions roll back side effects if a transition is halted. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked, use_transactions: true do before_transition do |vehicle| Message.create(content: "Starting transition") false # Halt the transition end event :ignite do transition :parked => :idling end end end vehicle = Vehicle.create vehicle.ignite # => false (transition halted) Message.count # => 0 (rolled back by transaction) ``` -------------------------------- ### Access Original Rails Enum Methods Source: https://github.com/state-machines/state_machines-activerecord/blob/master/README.md Demonstrates usage of the preserved original Rails enum methods. ```ruby order = Order.create(status: :pending) order.pending? # => true (Rails enum method) order.processing? # => false (Rails enum method) order.processing! # Sets status to :processing (Rails enum method) Order.pending # Rails enum scope Order.processing # Rails enum scope ``` -------------------------------- ### ActiveRecord Event Attribute Usage Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Demonstrates direct method calls, event attribute assignment, mass assignment, and validation handling for state transitions. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do event :process do transition pending: :processing end event :complete do transition processing: :completed end end end # Direct method calls order = Order.create order.process! # => true order.status # => "processing" # Using event attribute order = Order.create order.status_event = 'process' order.save # Fires process event order.status # => "processing" order.status_event # => nil (cleared after save) # Mass assignment order = Order.new(status_event: 'process') order.save order.status # => "processing" # Invalid event order = Order.create order.status_event = 'invalid_event' order.valid? # => false order.errors.full_messages # => ["Status event is invalid"] ``` -------------------------------- ### Define a basic state machine Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Defines a state machine on an ActiveRecord model with initial states and transition events. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do event :ignite do transition :parked => :idling end event :shift_up do transition :idling => :first_gear end end end vehicle = Vehicle.create vehicle.state # => "parked" vehicle.ignite # => true vehicle.state # => "idling" (persisted to DB) ``` -------------------------------- ### Define State Machine Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Register callbacks for transition lifecycle events, including support for after_commit hooks. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition :log_before after_transition :log_after after_transition :enqueue_job, after_commit: true event :ignite do transition :parked => :idling end before_save :validate_fuel end def log_before puts "Before transition" end def log_after puts "After transition" end def enqueue_job puts "Job enqueued after commit" end end ``` -------------------------------- ### Enabled integer state conversion Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Demonstrates the default behavior where state names are automatically mapped to integer values in the database. ```ruby StateMachines::Integrations::ActiveRecord.auto_convert_integer_state_attributes = true class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # Auto-mapped to 0 state :processing # Auto-mapped to 1 state :completed # Auto-mapped to 2 end end order = Order.create! order.status = :pending order.save # Database stores: 0 order.reload order.status # => "pending" (automatically converted from 0) ``` -------------------------------- ### Transparent Scope Filtering in Controllers Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/scopes.md Demonstrates how scopes return all records when nil is passed, simplifying search interface logic. ```ruby class VehiclesController < ApplicationController def index @vehicles = Vehicle.where(color: params[:color]) .with_state(params[:state]) # Returns all if params[:state] is nil .order(name: :asc) end end ``` -------------------------------- ### Define State Machine Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Callbacks receive the record and the transition object as arguments. ```ruby class Vehicle < ApplicationRecord state_machine do # Receives Transition in all callbacks before_transition { |vehicle, transition| ... } after_transition { |vehicle, transition| ... } after_failure { |vehicle, transition| ... } end end ``` -------------------------------- ### Transactional Safety in Transitions Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Illustrates that transitions are wrapped in transactions, ensuring that side effects are rolled back if a transition is halted. ```ruby class Message < ApplicationRecord end class Vehicle < ApplicationRecord state_machine do before_transition do |vehicle| Message.create(:content => 'Transitioning') false # Halt end event :ignite do transition :parked => :idling end end end vehicle = Vehicle.create vehicle.ignite # => false Message.count # => 0 (rolled back) ``` -------------------------------- ### Implement scope lambdas Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Logic for generating positive and negative state query scopes. ```ruby # For positive scope (with_state) lambda do |klass, values| if values.present? klass.where(attr_name => values) else klass.all end end # For negative scope (without_state) lambda do |klass, values| if values.present? klass.where.not(attr_name => values) else klass.all end end ``` -------------------------------- ### Batch processing with state scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/scopes.md Use find_each to iterate over large result sets efficiently when filtering by state. ```ruby Order.with_state(:pending).find_each do |order| order.process! end ``` -------------------------------- ### Access Gem Version Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Retrieves the current version string of the ActiveRecord integration gem. ```ruby puts StateMachines::Integrations::ActiveRecord::VERSION # => "0.200.0" ``` -------------------------------- ### Enum Integration and Prefixed Scopes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/scopes.md Illustrates how state machines on enum attributes generate prefixed scopes to avoid naming conflicts. ```ruby class Order < ApplicationRecord enum :status, { pending: 0, processing: 1, completed: 2 } state_machine :status do state :pending, :processing, :completed end end # Original Rails enum scopes (preserved) Order.pending # Find all pending orders (enum scope) Order.processing # Find all processing orders # State machine scopes (prefixed) Order.status_pending # Find all pending orders (state machine scope) Order.status_processing # Find all processing orders (state machine scope) # Negative state machine scopes Order.not_status_pending # Find all non-pending orders Order.not_status_processing # Find all non-processing orders ``` -------------------------------- ### Handle transaction rollback in after_failure Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Demonstrates that operations inside after_failure are subject to the transaction rollback if the transition fails. ```ruby class Vehicle < ApplicationRecord state_machine do after_failure do |vehicle, transition| # This runs in transaction and will be rolled back FailureLog.create(vehicle_id: vehicle.id) true # Must return true to allow rollback end before_transition do |vehicle| false # Trigger failure end event :ignite do transition :parked => :idling end end end vehicle = Vehicle.create vehicle.ignite FailureLog.count # => 0 (rolled back) ``` -------------------------------- ### Define Transition Conditions Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Use the 'if' option to specify a predicate method for conditional transitions. ```ruby class Vehicle < ApplicationRecord state_machine do event :ignite do transition :parked => :idling, if: :seatbelt_on? end end end ``` -------------------------------- ### Override initial state Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Shows how explicit attribute assignment during initialization overrides the default initial state. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending state :processing state :completed end end order = Order.new order.status # => "pending" # Explicit assignment overrides initial order = Order.new(status: :processing) order.status # => "processing" ``` -------------------------------- ### Handling Unmapped Integer States Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/errors.md Illustrates how unmapped integer values behave during deserialization and how to validate states to prevent invalid data. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # Mapped to 0 state :processing # Mapped to 1 end end # Directly set invalid integer in database (dangerous!) order = Order.create(status: :pending) order.update_column(:status, 999) # Skip validations order.reload order.status # => 999 (raw value, no matching state) ``` ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending state :processing end validates :status, inclusion: { in: %w(pending processing) } end order = Order.create order.update_column(:status, 999) # Bypasses validation order = Order.find(order.id) # Reloaded order.status # => 999 (invalid) order.valid? # Check for unmapped state ``` -------------------------------- ### Configure After Commit Callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Use the after_commit option to defer callback execution until the database transaction has successfully committed. ```ruby class Vehicle < ApplicationRecord state_machine do after_transition on: :ignite, after_commit: true do |vehicle| # Runs after transaction commits EngineWarmupJob.perform_later(vehicle) end end end ``` -------------------------------- ### Deferred Callbacks for Background Jobs Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/REFERENCE.md Uses after_commit to safely enqueue background jobs after a state transition is finalized. ```ruby class Order < ApplicationRecord state_machine do after_transition :on => :complete, :after_commit => true do |order| NotifyCustomerJob.perform_later(order.id) # Safe with GlobalID end end end ``` -------------------------------- ### Handle StateMachines::InvalidTransition Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/errors.md Shows how to rescue the InvalidTransition exception and use the non-bang alternative to avoid raising errors. ```ruby begin vehicle.ignite! rescue StateMachines::InvalidTransition => e puts "Cannot transition: #{e.message}" # Handle gracefully end ``` ```ruby # Non-bang version returns false instead of raising if vehicle.ignite # Success else puts "Transition failed" end ``` -------------------------------- ### Define states in an ActiveRecord model Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Demonstrates defining states with various value types including symbols, integers, and procs within a state_machine block. ```ruby class Order < ApplicationRecord state_machine :status, initial: :pending do state :pending # name: :pending, value: "pending" (string stored) state :active, value: 1 # name: :active, value: 1 (integer stored) state :archived, value: -> { 99 } # Dynamic value end end ``` -------------------------------- ### Halt transitions using callbacks Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/callbacks.md Return false from a before_transition callback to prevent the state change and roll back the transaction. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition do |vehicle| unless vehicle.safe? vehicle.errors.add(:base, 'Safety check failed') return false # Halt the transition end end event :ignite do transition :parked => :idling end end def safe? seatbelt_on && fuel_level > 0 end end vehicle = Vehicle.create(seatbelt_on: false) vehicle.ignite # => false (halted by before_transition) vehicle.state # => "parked" (unchanged, rolled back) ``` -------------------------------- ### Accessing Transition Attributes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Use the transition object within a before_transition callback to access metadata like the source state, target state, and trigger event. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition do |vehicle, transition| puts "Transitioning from #{transition.from} to #{transition.to} via #{transition.trigger}" end event :ignite do transition :parked => :idling end end end vehicle = Vehicle.create vehicle.ignite # Prints: "Transitioning from parked to idling via ignite" ``` -------------------------------- ### Define after_initialize hook Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Internal hook called after machine initialization to set up enum integration and register integer types. ```ruby def after_initialize ``` -------------------------------- ### initialize_enum_integration Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/machine.md Initializes enum integration when an enum is detected on the machine's attribute. Called automatically during machine initialization. ```APIDOC ## initialize_enum_integration() ### Description Initializes enum integration when an enum is detected on the machine's attribute. Called automatically during machine initialization. ### Return Value Returns nil. Sets @enum_integration on the machine. ``` -------------------------------- ### Configure transaction usage Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/configuration.md Controls whether state transitions are wrapped in database transactions. ```ruby state_machine :status, use_transactions: false do ... end ``` -------------------------------- ### Configure I18n Error Messages Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/types.md Defines the default I18n error message templates for state machine transitions. ```yaml en: activerecord: errors: messages: invalid: "is invalid" invalid_event: "cannot transition when %{state}" invalid_transition: "cannot transition via %{event}" ``` -------------------------------- ### Detecting Transition Rollback Causes Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/errors.md Demonstrates how to inspect the errors object after a failed transition to distinguish between custom logic failures and model validation errors. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do before_transition do |vehicle| # Returning false triggers rollback vehicle.errors.add(:base, 'Safety check failed') unless vehicle.safe? vehicle.safe? end event :ignite do transition :parked => :idling end end validates :name, presence: true end vehicle = Vehicle.create(name: '') vehicle.ignite # => false # Determine cause if vehicle.errors[:base].any? puts "Transition blocked: #{vehicle.errors[:base].join(', ')}" elsif vehicle.errors[:name].any? puts "Validation failed: #{vehicle.errors[:name].join(', ')}" end ``` -------------------------------- ### Implement Conditional Transitions in ActiveRecord Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/events-transitions.md Use the :if option to define guard conditions for state transitions. Transitions return false if the condition is not met. ```ruby class Vehicle < ApplicationRecord state_machine :initial => :parked do # Transition from any state except parked event :ignite do transition [:idling, :first_gear] => :idling end # Guard with conditions event :accelerate do transition :idling => :first_gear, :if => :seatbelt_on end end end vehicle = Vehicle.create vehicle.seatbelt_on = false vehicle.accelerate # => false (condition not met) vehicle.seatbelt_on = true vehicle.accelerate # => true (condition met) ``` -------------------------------- ### Retrieve Named States Source: https://github.com/state-machines/state_machines-activerecord/blob/master/_autodocs/api-reference/integer-type.md Returns all non-nil states in the order they were defined. ```ruby def named_states ```