7

in state_machine I used to do

state :cancelled do
  validates_presence_of :user
end

it would automatically cancel the transition if user was not present.

How do we add similar validations to specific states in aasm?

Raz
  • 8,981
  • 4
  • 19
  • 18

2 Answers2

7

I can offer 2 options:

the first:

validates_presence_of :sex, :name, :surname, if: -> { state == 'personal' }

the second

event :fill_personal do
  before do
    instance_eval do
      validates_presence_of :sex, :name, :surname
    end
  end
  transitions from: :empty, to: :personal
end
eugene_trebin
  • 1,485
  • 1
  • 16
  • 29
-1

I'm using Rails 5 with AASM gem to manage model states and I faced the same situation with validations to apply a specific state. What I did to make it work the way I wanted to, was:

class Agreement < ApplicationRecord
    include AASM

    aasm do
        state :active, initial: true
        state :grace
        state :cancelled

        event :grace do
            transitions from: :active, to: :grace
        end

        event :cancel do
            transitions to: :cancelled, if: :can_cancel_agreement?
        end
    end

    private

    def can_cancel_agreement?
        self.created_at.today?
    end
end

I this way the validation runs before the transition is done. And the transition is never completed if the validation fails.

I hope it could be useful for somebody facing the same need.

alexventuraio
  • 8,126
  • 2
  • 30
  • 35