stateful_enum icon indicating copy to clipboard operation
stateful_enum copied to clipboard

Is there a way for the event methods to skip validations?

Open terenceponce opened this issue 7 years ago • 3 comments

I want any state changes to exclusively go through the state machine and prevent other developers, including myself, to change the state directly via #create or #update. Here's an example:

class User < ApplicationRecord
  enum status: [:active, :inactive, :banned] do
    event :deactivate do
      transition :active => :inactive
    end

    event :ban do
      transition :active => :banned
    end
  end

  validates :status, inclusion: { in: %w(active) }, on: :create
  validates :status, absence: true, on: :update
end

As you can see, the validations make sure that the following code won't work:

User.create(state: "inactive")
User.create(state: "banned")
user.update(state: "inactive")
user.update(state: "banned")

Unfortunately, the event methods provided by stateful_enum won't work because it will have to go through the same validations. Is there a way for me to skip these validations when the state change comes from stateful_enum?

terenceponce avatar May 11 '18 08:05 terenceponce

Interesting idea. I’ve never thought of that, but suggestions with implementations are welcome!

amatsuda avatar May 11 '18 08:05 amatsuda

Sorry, just closed the issue by accident, but I’ll leave this opened until someone actually implements this.

amatsuda avatar May 11 '18 08:05 amatsuda

Not exactly what you're trying to achive @terenceponce, but I prevent records from transitioning to an invalid state through #create or #update methods in this PR https://github.com/amatsuda/stateful_enum/pull/49

jairovm avatar Apr 14 '20 22:04 jairovm