Robin Winton
Robin Winton

Reputation: 601

How can I separate the validations from the model

I have some very big models that I must migrate to the latest version of Rails. These models have quite a bunch of validations(User has aprox. 50 validations).

Is it possible to move all these validations in another file? Say app/models/validations/user_validations.rb. And if it is can someone provide an example, please?

Upvotes: 7

Views: 1091

Answers (1)

A Fader Darkly
A Fader Darkly

Reputation: 3636

You can use concerns for this:

# 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 to namespace your concerns depending on your autoload path configuration:

# app/models/validations/user.rb

require 'active_support/concern'

module Validations
  module User
  ...


# app/models/user.rb

class User
  include Validations::User

From a style perspective you may want to think about why you have so many validations. Shunting them into a module will slim down the model file, but effectively the class still carries all that code around with it. you're effectively sweeping the problem under the carpet.

Are you using a lot of different forms with different validation requirements? If so, you can use form objects (which include ActiveModel functionality) to encapsulate the validations and processing needed for each form, taking the strain off the models.

Do your models have an insane number of fields? Maybe your user object needs to be composed from smaller objects like a profile, address, avatar, etc.

Of course, this is outside the scope of a version migration!

If you can't or don't want to use ActiveRecord concerns (which have some dependency management code that you may not want to carry around), you can use the excellent and tiny plug-in 'augmentations' or the derived gem:

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

This uses a very similar syntax and far less code. It also doesn't use the term 'concerns', which can mean something else in the OO terminology for different languages/frameworks.

Upvotes: 10

Related Questions