Abhi On Rails

Ruby On Rails - What I learned recently

State Machine

In some application we need to track the state of a model. For example, a user requested for signup. Admin has to approve the user for the user to login. Admin has the option to reject the user also. So the status of the user model will be in one of the following states [pending, approved, rejected].

The famous plugin used for tracking the state is aasm. You can install Acts as state machine using:

sudo gem install aasm

Then in the user model you have to include the plugin

include AASM

Then specify which field you want to use as the state.

aasm_column :status

Now you can write the states of the model:

aasm_state :pending 
aasm_state :approved 
aasm_state :rejected

You can set initial state using:

aasm_initial_state :pending

Now we need the events to change the state:

aasm_event :approve do
  transitions :to => :approved, :from => [:pending]
end


aasm_event :reject do
  transitions :to => :rejected, :from => [:pending]
end

This is all we need in model.

Now to change the state of the model object you can use:

user.approve!  #To approve the user
user.reject!      #To reject the user

If you want to do something while the state of the model is change from one state to another you can call the method at the time of state change using:

aasm :approved, :enter => entered_to_apporoved, :exit => exit_from_approved

At the time of state definition you can specify the enter method and exit method to call.


blog comments powered by Disqus
time_diff - a gem for calcu... →
← Heroku