benzelano / test_lh_import

1 stars 0 forks source link

Exception when changing state of an existing record with a nil state #125

Closed benzelano closed 13 years ago

benzelano commented 13 years ago

Nicolas Blanco opened this issue

state_machine is a great plugin but I’ve found a problem.

When you add a state_machine to an existing ActiveRecord model and load an existing model, the state of the model is therefore nil, state_machine raises an exception when you call an event.

@@@

u = User.last => # u.state => nil u.activate! NoMethodError: You have a nil object when you didn’t expect it! The error occurred while evaluating nil.name from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/event.rb:166:in transition_for’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/event.rb:190:infire’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/event.rb:242:in add_actions’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/machine.rb:512:incall’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/machine.rb:512:in activate’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/event.rb:247:insend’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/event.rb:247:in add_actions’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/machine.rb:512:incall’ from /Library/Ruby/Gems/1.8/gems/pluginaweek-state_machine-0.7.6/lib/state_machine/machine.rb:512:in `activate!’ from (irb):3 @@@

original LH ticket

This ticket has 0 attachment(s).

benzelano commented 13 years ago

(from [27361129a8607b5922995e656701428ed617ed18]) Fix events not failing with useful errors when an object’s state is invalid [#25 state:resolved] http://github.com/pluginaweek/state_machine/commit/27361129a8607b5922995e656701428ed617ed18

benzelano commented 13 years ago

Thanks for the report. As you might notice from the above change, this problem occurs because the state of the record (nil in your case) is unknown to the state machine. In order for the state machine to work on an existing record, you have to make sure that the existing records are all in valid states. If nil is valid state in this case, then you can define it like so:

class User
  state_machine do
    ...
    state nil
  end
end

This will define a nil state and will therefore not error out when trying to transition on an object with that state.

Hope this helps!