如何将默认AASM状态添加到现有模型

Mas*_*sha 3 ruby-on-rails aasm acts-as-state-machine

我在rails中有一个现有模型,我想向它添加AASM状态.

根据我的理解,我应该首先通过迁移向我的数据库添加一个状态列,然后将一些状态添加到我的rails模型中.如何根据另一列中的值设置默认状态值?

我在正确的轨道上吗?

Pet*_*tee 5

你走在正确的轨道上.您可以在迁移本身中为新记录设置初始状态.

使用:default选项如下所示.如果每条记录具有完全相同的起始状态,这将非常有用:

# Assuming your model is named Order
class AddStateToOrders < ActiveRecord::Migration
  add_column :orders, :state, :string, :default => 'new'
end
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用简单的ruby位来添加列后设置每个记录的状态.如果记录的初始状态是以某种为条件的,则更有用.

# 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
Run Code Online (Sandbox Code Playgroud)