简体   繁体   中英

State machine and params in a rails app

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
  • I do it in a before_save method that will be triggered by an update. This one is more complicated as I need to check if start_date has changed, and if yes I check the date and update it, before changing the state.

-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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM