stateful_enum icon indicating copy to clipboard operation
stateful_enum copied to clipboard

Prevent going to an invalid transition when using setter directly

Open jairovm opened this issue 5 years ago • 4 comments

Hi @amatsuda !

I've been playing around with this gem and I really like how AR enum is extended and how that brings us state_machine core functionality while still making use of an Integer column in the DB side.

WHY

There should be something that prevents records from transitioning to an invalid state through default AR methods like update(status: 1), status = 1

HOW

  • Extended AR enum setters
  • Desired state is being validated against stateful_enum.possible_states
  • If state is not included in the possible_states array an exception is thrown
  • This transition validation is only executed when:
    • record's current state is not blank
    • desired state is different that current state

Also, I fixed/added tests.

P.S. This PR does not add support for triggering before/after callbacks when using AR setters

Please, let me know you thoughts about this.

Thank you

jairovm avatar Apr 14 '20 00:04 jairovm

@jairovm Thank you for a fabulous patch!

I guess I totally understand where you came from, and yes I'm also hoping to solve that problem.

However, I generally don't want my models to raise an error when I just put an attribute value. IOW, immediately running a validation with an attribute write doesn't seem like a regular Rails way.

How about changing the implementation to just automatically add a simple model validation?

amatsuda avatar May 01 '20 05:05 amatsuda

@amatsuda thanks for taking the time to review this.

It's funny that after having this fix running for a few days in our rails app my team and I decided to move this patch to a rails validation 👍

So yes, I'll work on that and let you know when it's ready.

jairovm avatar May 07 '20 00:05 jairovm

@jairovm 👍👍👍

amatsuda avatar May 07 '20 01:05 amatsuda

Hi @amatsuda!

I'd like to continue working on these changes, please let me know your comments when you get a chance 👌🏼

Thanks for your time 😃

jairovm avatar Oct 02 '20 06:10 jairovm