benzelano / test_lh_import

1 stars 0 forks source link

Enhancement: Option to validate when leaving a state, rather than when entering #124

Closed benzelano closed 13 years ago

benzelano commented 13 years ago

Patrick Klingemann opened this issue

Aaron,

Thanks for your great work on this plugin/gem, it is quite useful to me. I am building a workflow form with state machine in which the form that is displayed is based on the state of a state machine. The issue I’m having is that I need to validate certain fields based on the state that the state machine is in currently, and state_machine’s behavior validates fields based on the state to which the state machine is transitioning.

I am wondering if this has been considered as an option, also I would be glad to help develop an option to accomplish this. You may a have a strong opinion against this, but otherwise, could you provide me some guidelines on how I might tackle this issue? I am using ActiveRecord with Rails 2.3.2.

Once again, thanks for your contributions to the community.

Patrick Klingemann

original LH ticket

This ticket has 0 attachment(s).

benzelano commented 13 years ago

Hi Patrick,

Unfortunately we can’t target specific validations to run prior to transition or specific ones to run after transition. However, what I’ve seen in the past is something like so:

@@@ ruby class Vehicle < ActiveRecord::Base state_machine do before_transition any => :idling do |vehicle| unless vehicle.allowed_to_continue? vehicle.errors.add :base, ’is not allowed to do this’ false end end end end @@@

What you’ll notice in the example is that it uses before_transition to target specifically when to validate the state of the record. When that transition occurs, the custom validation code is run. By adding an error and returning false, the event will fail and there will be errors to report to the user.

Unfortunately you don’t have the advantage of using the built-in ActiveRecord validations in this case. I’m sure it could be done through some fancy hackery, but this should give you a good start down the right path.

If you have any questions or want to discuss it more, feel free to post on the Google Groups mailing list.

Best of luck!