Reputation: 3829
I am in the process of implementing state machine to a model having a subscription behaviour usin AASM. I want a state machine to be able to trigger actions when changing states.
Currently I use an update action that will fail if the date is not correct thanks to callbacks.
class Contrat
validate :active_start_is_valid
end
I want to use state machine but all the implementations I imagine seems messy to me :
-I create a class method or a service object with this kind of method :
def start_subscription(date)
date = validate_input_date(date)
@contrat.start_date=date
@contrat.activate!
end
-The controller action for activation is a limited update action (filtered with a custom params require) that will do something like that :
if @contrat.update_attributes
@contrat.activate!
end
I am really not comfortable with any of theses. State machine articles, for rails or not, never mention params to event, is there some other pattern I should be aware of?
Am I missing something obvious?
Upvotes: 1
Views: 359
Reputation: 2129
This is not how you should implement state machine, you should create your models with and state field indicates the state of the record then decide what are the state's for an Object and use transition:
if you want to indicate the initial state use:
state_machine :state, initial: :started do
...
end
if you wish the create transition:
event :start do
transition [:created] => :started
end
do jobs on transition:
after_transition [:created] => :started, do: :send_mail
read more here:
https://github.com/pluginaweek/state_machine
Upvotes: 1