After a feedback from another article, I‘ve realised that there’s more to say about validation extraction from ActiveRecord Models.

At linkedcare we’re building an EHR system and with time we realised that our Models we’re becoming huge, not only because we were putting a lot of business logic on it, but also because validations we’re growing feature by feature. With the shifting of business logic to separated classes, validations were extracted too and it couldn’t make more sense.

Let’s say we have a Blog (I know… It’s always a Blog) and there are two types of users: Writer and Admins. One writes a post and waits for the other to review and publish. This means that there are two states for a post, lets say draft and published.

Saving a post for draft and saving for published have different constrains. A draft does not need to be in a category and does not need a min/max body length, for example. Why this two types of validations are in the Model if they have two contexts to be called? Contexts can be something like a Create, Update or a user role, like Admin or Writer. How many times we see user.save(validate: false) in our code? Or something like this?

There are particular contexts that most validations do not need to run and there are others that are complex enough that will be easier to understand if we create a class that only has that responsibility.

For us it was easier to extract those validations for Use Case objects, because all of our business logic is Use Case driven, so we can have Post::ValidatePublished and Post::ValidateDraft Use Cases and just add as dependencies for other Use Cases. But the main ideia is that validations have a tendency to be context dependent, so is a good practice to extract them from the model to be used in those particular contexts.