Dynamically set initial state with aasm gem
Asked Answered
D

2

5

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?

Deery answered 28/10, 2017 at 9:52 Comment(0)
K
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.

Keirakeiser answered 12/3, 2019 at 15:4 Comment(0)
F
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.

Foskett answered 1/11, 2017 at 16:58 Comment(1)
how would you use aasm_ensure_initial_state without using it in an after_create?Manor

© 2022 - 2024 — McMap. All rights reserved.