StateMachines 主动记录集成
The Active Record 8.0+ integration adds support for database transactions, automatically saving the record, named scopes, validation errors.
Add this line to your application's Gemfile:
gem 'state_machines-activerecord'And then execute:
$ bundleOr install it yourself as:
$ gem install state_machines-activerecordFor the complete usage guide, see http://www.rubydoc.info/github/state-machines/state_machines-activerecord/StateMachines/Integrations/ActiveRecord
class Vehicle :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
endUsage of the generated scopes (assuming default column state):
Vehicle.with_state(:parked) # also plural #with_states
Vehicle.without_states(:first_gear, :second_gear) # also singular #without_stateState scopes will return all records when nil is passed, making them perfect for search filters:
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)When your ActiveRecord model uses Rails enums and defines a state machine on the same attribute, this gem automatically detects the conflict and provides seamless integration. This prevents method name collisions between Rails enum methods and state machine methods.
class Order :cancelled
end
end
endWhen enum integration is detected, the gem automatically:
pending?, processing?, etc.)status_pending?, status_processing?, etc.)Order.status_pending, Order.status_processing, etc.)Original Rails enum methods (preserved):
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 scopeGenerated state machine methods (prefixed):
# 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 scopeThe integration provides a comprehensive introspection API for advanced use cases:
…Integer columns whose states don't declare explicit values are converted transparently: application code reads state names while the database stores integers (mapped by definition order).
class Order "approved"
# The database stores 1.Machines where every state declares an explicit integer value keep the classic
raw-integer behavior automatically: reads return the integer and status_name
returns the state name:
class LegacyOrder 1
order.status_name # => :approved
# The database stores 1.Applications that want no type conversion at all can disable it during boot, before defining affected state machines:
# config/initializers/state_machines.rb
StateMachines::Integrations::ActiveRecord.auto_convert_integer_state_attributes = falseWith this setting disabled, integer-backed state attributes are left entirely to ActiveRecord's normal integer handling.
The enum integration supports several configuration options:
prefix (default: true) - Adds a prefix to generated methods to avoid conflictssuffix (default: false) - Alternative naming strategy using suffixes instead of prefixesscopes (default: true) - Controls whether state machine scopes are generatedAs mentioned in StateMachines::Machine#state, you can define behaviors,
like validations, that only execute for certain states. One important
caveat here is that, due to a constraint in ActiveRecord's validation
framework, custom validators will not work as expected when defined to run
in multiple states. For example:
class Vehicle :speed_is_legal validation will only get run
for the :second_gear state. To avoid this, you can define your
custom validation like so:
```ruby
class Vehicle < ApplicationRecord
state_machine do
state :first_gear, :second_gear do
validate {|vehicle| vehicle.speed_is_legal}
end
end
endgit checkout -b my-new-feature)git commit -am 'Add some feature')git push origin my-new-feature)暂无开放 Issues,或尚未同步最近议题。