Search code examples
ruby-on-railsvalidationruby-on-rails-4activerecordcustom-validators

Rails: Using same custom validation method for multiple models


I have this method in 3 models, so I'd like to extract it and DRY things up. I'm also having problem with the default value of the attr. When the field is empty it will be evaluated as empty string "" instead of nil, so I have to write the conditional in the method to avoid adding the "http" to empty string.

Where should I put the method and how can I include it in the models?

Should I optimize the method? If so, where and how can I set the default attr value to nil (rails/db/both)?

before_validation :format_website

def format_website
  if website == ""
    self.website = nil
  elsif website.present? && !self.website[/^https?/]
    self.website = "http://#{self.website}"
  end
end

Solution

  • You can put your method in the app/models/concerns folder, for example, as Validatable module (i.e. validatable.rb):

    module Concerns::Validatable
      extend ActiveSupport::Concern
    
      def format_website
        if website.blank?
          self.website = nil
        elsif !self.website[/^https?/]
          self.website = "http://#{self.website}"
        end
      end
    
    end
    

    And then include it in each models as

    include Concerns::Validatable