Passing variables to Rails StateMachine gem transitions

前端 未结 5 2138
猫巷女王i
猫巷女王i 2021-02-05 10:07

Is it possible to send variables in the the transition? i.e.

@car.crash!(:crashed_by => current_user)

I have callbacks in my model but I nee

5条回答
  •  离开以前
    2021-02-05 10:59

    Another common pattern (see the state_machine docs) that saves you from having to pass variables between the controller and model is to dynamically define a state-checking method within the callback method. This wouldn't be very elegant in the example given above, but might be preferable in cases where the model needs to handle the same variable(s) in different states. For example, if you have 'crashed', 'stolen', and 'borrowed' states in your Car model, all of which can be associated with a responsible Person, you could have:

    state :crashed, :stolen, :borrowed do
      def blameable?
        true
      end
    
    state all - [:crashed, :stolen, :borrowed] do
      def blameable?
        false
      end
    

    Then in the controller, you can do something like:

    car.blame_person(person) if car.blameable?
    

提交回复
热议问题