Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

Peter's answer is good, but it has one defect. You'll need to write a new migration if you change default state. So,

class AddStateToOrders < ActiveRecord::Migration
  def self.up
    add_column :orders, :state, :string
    Order.update_all(aasm_state: 'new') # it will apply just for existing records with empty state.
  end

  def self.down
    remove_column :orders, :state
  end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top