AASM dynamic state machine

This post shows you how to create a state machine to your ActiveRecord model. States are stored in database. In this example we use Rails5 and PostgreSQL.


A task belongs to a project. A project has one project type. Project type describes the task’s states.


Project type migration file:

Transitions stores the transition in JSON format. In this example the initial state of the newly created task is todo.

The task state can change from todo to done after getting the doit event.

The project type class is simple:

And here is our Task class:

If we test the code

It works!

2 replies
  1. Vlatko
    Vlatko says:

    I really don’t think this is the right approach. Overriding ‘initialize’ to an ‘ActiveRecord’ class even with calling ‘super’ on it is a big dangerous, or at least deserves a bit more explanation. Plus I’m curious what is the purpose of the ‘create_state’ method and the ‘save’ method? Can you please explain a bit more?


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *