Setting a callback whose action depends on the previous state of the object

I've been reading about ActiveRecord::Callbacks and they're really
cool. But I have a complex need I'm not sure they answer.

Let's say we have a User model. User has a #status attribute, which
can be either "active", "closed" or "blocked".

I want to set a callback to perform an action if an "active" User has
been blocked. So I need to know:

1. That the user has at first been in "active" status.
2. That his status has been set to "blocked".

I need to set the callback when someone tries to save him in this
state, so to sum up:

I need to run some logic when someone updates a user.status from
'active' to 'blocked'.

Any idea how?

Thinking completely off the top of my head (e.g., none of this has actually been run), I'd say you could hook into the status writer and set a flag for later use in a before_save callback.

before_save :handle_newly_blocked

def status=(new_status)
   if self.status == 'active' && new_status == 'blocked'
     @newly_blocked = true
   write_attribute(:status, new_status)

def handle_newly_blocked
   if @newly_blocked
     # .. handle it ..


Rob Biedenharn

Although your example is a simple state machine, I am a big fan of acts_as_state_machine.


Sorry for the late response, but I couldn't resist telling you to look
at the acts_as_state_machine plugin. It lets you program transition
logic like you're describing declaratively.