3

I've an ActiveRecord model. I'd like to set an initial state depending on its attributes at the initialization. Here is my condition:

self.expected_delivery_date.blank? ? :in_preparation : :waiting

Is there a way to do that? Is it a bad idea?

Tom Copeland
  • 1,221
  • 10
  • 10
Camille
  • 678
  • 6
  • 23

2 Answers2

4

State accepts a Proc, so yes, you can do this

initial_state lambda { |your_model|
    your_model.expected_delivery_date.blank? ? :in_preparation : :waiting
}

See more examples here.

Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
2

You could define an aasm hook method and set the state there:

class User < ActiveRecord::Base
  include AASM
  aasm do
    state :submitted, initial: true
    state :started
  end
  def aasm_ensure_initial_state
    self.aasm_state = :started
  end
end

That seems reasonable to me; you could give the most common initial state the initial: true option and then use logic in aasm_ensure_initial_state to set the less common initial state.

Tom Copeland
  • 1,221
  • 10
  • 10