views:

229

answers:

2

I'd like to create a callback function in rails that executes after a model is saved.

I have this model, Claim that has a attribute 'status' which changes depending on the state of the claim, possible values are pending, endorsed, approved, rejected

The database has 'state' with the default value of 'pending'.

I'd like to perform certain tasks after the model is created on the first time or updated from one state to another, depending on which state it changes from.

My idea is to have a function in the model:

    after_save :check_state

    def check_state
      # if status changed from nil to pending (created)
      do this

      # if status changed from pending to approved
      performthistask
     end

My question is how do I check for the previous value before the change within the model?

A: 

I recommend you have a look at one of the available state machine plugins:

Either one will let you setup states and transitions between states. Very useful and easy way of handling your requirements.

Toby Hede
I'm giving rubyist-aasm a try.Lets say I have class Claim < ActiveRecord:: Base include AASM aasm_column :status aasm_initial_state :pending aasm_state :pending, :enter => :enter_pending def enter_pending Notifier.deliver_pending_notification(self) endendAnd my status field in my database has the default value of "pending".If I were to do a Claim.create without filling in the status field (so that it will run 'pending'), will AASM run the 'enter_pending' method?
+3  A: 

You should look at ActiveRecord::Dirty module: You should be able to perform following actions on your Claim model:

  claim.status_changed?  # returns true if 'status' attribute has changed
  claim.status_was       # returns the previous value of 'status' attribute
  claim.status_change    # => ['old value', 'new value'] returns the old and new value for 'status' attribute

Oh! the joys of Rails!

KandadaBoggu