Status Transition Validation using FSM in elixir

I have a Postgres table which has a status column and someone is asking me to update the status so I have to do a validation if that transition is possible. So How can I do that?
For example: I can have 4 status like procured, deployed, deployment_need_fix and retired.
So I can’t directly change the status column to retired from procured or retired to deployed. Procured can go to deployed state.

PS: I am not able to add machinery dep in my phoenix giving me Hex resolution error.
This is the error I am getting when adding machinery {0.17.0}
Failed to use “cowboy” (version 2.6.3) because
machinery (version 0.12.1) requires ~> 1.0
plug_cowboy (version 2.0.2) requires ~> 2.5
mix.lock specifies 2.6.3

The easiest is to use function matching to simulate the FSM:

@spec valid_transistion(from, to) :: boolean
valid_transistion(procured, deployed), do: true

valid_transistion(_, _), do: false

You can then use this function within an Ecto.Changeset marking the changeset invalid which would bar it from doing an update.

2 Likes