makandra/rails_state_machine

State is set wrong after validation error

denzelem opened this issue · 1 comments

class User
  include RailsStateMachine::Model

  validates :name, presence: true, if: :approved?

  state_machine do
    state :draft, initial: true
    state :approved

    event :approve do
      transitions from: :draft, to: :approved
    end
  end
end
user = User.create!(name: 'John')
user.state => 'draft'
user.approve => true
user.state => 'approved'

user.name = nil
user.save! => ActiveRecord::RecordInvalid (Validation failed: Name can't be blank)
user.state => 'draft' # nope - should be approved

user = User.find(user.id)
user.state => 'approved'
user.name = nil
user.save! => ActiveRecord::RecordInvalid (Validation failed: Name can't be blank)
user.state => nil # nope - should be approved

Tested with AR 5.2.1. It seems to be a logical error within the revert_state procedure of rails_state_machine.

1.1.2 fixes these issues