Validate current value of attribute before changing it

I have a Resource with attribute:

   attribute :status, :atom do
      constraints one_of: [:unseen, :incomplete, :complete]
      default :unseen
    end

I want to create an action:

    update :incomplete do
      change set_attribute(:status, :incomplete)
    end

Except I want to validate that the current value of :status isn’t :complete, basically prevent improper state changes from one state to another from happening.

I looked at:

attribute_does_not_equal(attribute, value)
Validates that an attribute is not being changed to a specific value, or does not equal the given value if it is not being changed.

But as it says there, it only validates the current value of the attribute, IF it’s NOT being changed.

You can write your own validation Validations — ash v2.17.10

It takes in the changeset, which holds the current data in changeset.data and the changes that will be applied in changeset.attributes.

There are also get_attribute and get_data as well as changing_attribute helper functions you can use.

That way you can compare the current and future state and see if the transition is valid.

There is also Get Started With State Machines — ash_state_machine v0.2.2 which can help if it fits your usecase

1 Like

Oh, nice! Lots of good options here. I thought I might be missing a built-in that would do it. Ash state machine looks like a good option for correctness.