ruby-on-railsaasmacts-as-state-machine

How to add a default AASM state to existing model


I have an existing model in rails and I want to add AASM states to it.

From my understanding, I should add a state column to my database through migrations first and then add some states to my rails model. How do I set a default state value according to a value in another column?

Am I on the right track at all?


Solution

  • You are on the right track. You can set the initial state for new records in the migration itself.

    Either use the :default option as follows. This is most useful if every record has the exact same starting state:

    # Assuming your model is named Order
    class AddStateToOrders < ActiveRecord::Migration
      add_column :orders, :state, :string, :default => 'new'
    end
    

    Or you can use a simple bit of ruby to set the state of each record after the column is added. More useful if the initial state of records is conditional on something.

    # Still assuming your model is named Order
    class AddStateToOrders < ActiveRecord::Migration
      add_column :orders, :state, :string
    
      # Loop through all the orders, find out whether it was paid and set the state accordingly
      Order.all.each do |order|
        if order.paid_on.blank?
          order.state = 'new'
        else
          order.state = 'paid'
        end
        order.save
      end
    end