pluginaweek/state_machine — Issue #142: Transition exception should show failed validation
Author: jaylevitt
Created: 2011-11-17 18:16:41+00:00
State: open

I have a state machine like:

class AbsenceValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.nil?
record.errors[attribute] << (options[:message] || "must be nil")
end
end
end

class SurveyTaking < ActiveRecord::Base
belongs_to :pending_question

state_machine :state do
state :started {validates :pending_question, :presence => true}
state :completed {validates :pending_question, :absence => true}

event :complete do
transition :started => :completed
end
end
end

st = SurveyTaking.new
st.pending_question_id = nil
st.complete! #=> StateMachine::InvalidTransition: Cannot transition state via :complete from :started

ActiveRecord (without state_machine) will actually give you the validation in the exception, which is quite helpful:

me = User.find(1)
me.gender = 'neither'
me.valid? #=> false
me.save! #=> ActiveRecord::RecordInvalid: Validation failed: Gender is not included in the list

I think this was at the root of my #121 issue.