Reputation: 9751
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?
Upvotes: 7
Views: 3807
Reputation: 10114
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.
Upvotes: -1
Reputation: 1553
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
Upvotes: 7