views:

20

answers:

1

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?

+2  A: 

I don't think you can pass params to events with that gem, so maybe you could try storing the current_user on @car (temporarily) so that your audit callback can access it.

In controller

@car.driver = current_user

In callback

after_crash do |car, transition|
   create_audit_log car.driver, transition
end

Or something along those lines.. :)

keeran
Thanks Keeran. This is basically what I ended up doing in the end. As the attribute has no permanence - any thoughts on how you could do this without creating a new field in the DB?
Kevin Monk
You could try adding an attr_accessor for :driver, but I'm not sure if the callback will reload / use a 'fresh' instance of the model (and so wipe the temp var).
keeran