简体   繁体   中英

rails state_machine refactoring

doing a simple order processing with state machine, just want to record changes in DB after each event. Maybe someone have any ideas on how I can refactor this: so that i wouldn't need many record methods and after_transition

def record
   self.status_transition.update(:event => "placed", :from => "draft" , :to => "placed" )
end

def record_cancel
   self.status_transition.update(:event => "canceled", :from => "placed" , :to => "draft" )
end

state_machine initial: :draft do
state :draft, value: 0
state :placed, value: 1
state :paid, value: 2
state :canceled, value: 3
after_transition :on => :place, :do => :record
after_transition :on => :cancel, :do => :record_cancel


event :place do 
  transition :draft => :placed
end
event :cancel do 
  transition :placed => :draft
end
event :pay do 
  transition :placed => :paid
end
end

You can define a generic transition callback, such as

after_transition any => any do |order, transition|
  order.status_transition.update(event: transition.event,
                                 from:  transition.from, 
                                 to:    transition.to)
end

See StateMachine::Transition for the methods you can call on the transition block argument.

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