Search code examples
ruby-on-railsstate-machine

Passing variables to Rails StateMachine gem transitions


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 need to send them the user who instigated the transition

after_crash do |car, transition|
  # Log the car crashers name
end

I can't access current_user because I'm in the Model and not the Controller/View.

And before you say it... I know I know.

Don't try to access session variables in the model

I get it.

However, whenever you wish to create a callback that logs or audits something then it's quite likely you're going to want to know who caused it? Ordinarily I'd have something in my controller that did something like...

@foo.some_method(current_user)

and my Foo model would be expecting some user to instigate some_method but how do I do this with a transition with the StateMachine gem?


Solution

  • If you are referring to the state_machine gem - https://github.com/pluginaweek/state_machine - then it supports arguments to events

    after_crash do |car, transition|
      Log.crash(car: car, crashed_by: transition.args.first)
    end