How to separate validations from a model

I have very large models that I have to port to the latest version of Rails. These models have quite a few validations ( User has approximately 50 confirmations).

Can all these checks be transferred to another file? Say app/models/validations/user_validations.rb . And if anyone can provide an example, please?

+5
source share
1 answer

You can use the following problems:

 # app/models/validations/user_validations.rb require 'active_support/concern' module UserValidations extend ActiveSupport::Concern included do validates :password, presence: true end end # app/models/user.rb class User include UserValidations end 

You may need / want the namespace to indicate your problems depending on the configuration of the startup path:

 # app/models/validations/user.rb require 'active_support/concern' module Validations module User ... # app/models/user.rb class User include Validations::User 

In terms of style, you might wonder why you have so many validations. Shunting them into a module will reduce the model file, but in reality the class still carries all this code. You effectively sweep the problem under the carpet.

Do you use many different forms with different validation requirements? If so, you can use form objects (which include ActiveModel functionality) to encapsulate the validation and processing needed for each form, removing stress from the models.

Do your models have an insane amount of fields? Perhaps your custom object should be made up of smaller objects such as profile, address, avatar, etc.

Of course, this goes beyond version migration!

If you can't or don't want to use ActiveRecord problems (which have some dependency management code that you might not want to port), you can use the excellent and tiny add-on plugins or derivative pearls:

https://github.com/chemica/augmentations-gem

In this case, very similar syntax and much less code is used. He also does not use the term β€œproblems”, which may mean something else in OO terminology for different languages ​​/ frameworks.

+7
source

Source: https://habr.com/ru/post/1200330/


All Articles