Adding uniqueness validation for dynamic attributes in rails

448 views Asked by At

We have a multi-tenant application where validation differs for each account. We could easily achieve this for presence validation like the below,

module CommonValidator
  def add_custom_validation
    required_fields = get_required_fields
    return if required_fields.blank?

    validates_presence_of required_fields.map(&:to_sym)
  end
end

class ApplicationRecord < ActiveRecord::Base
  include Discard::Model
  include CommonValidator
end

Then we have to add uniqueness validation based on account, so tried like the same. but getting undefined method error. Is there any way that I could get this work?

module CommonValidator
  def add_custom_validation
    unique_fields = ['first_name']
    validates_uniqueness_of unique_fields.map(&:to_sym) if unique_fields.present?
  end
end

error

1

There are 1 answers

0
Anuj On

validates_uniqueness_of is actually a class method (defined in ActiveRecord::Validations::ClassMethods), hence you are not able to call it from the context of the object.

Whereas validates_presence_of is both a helper method, and a class method (defined in ActiveModel::Validations::HelperMethods and ActiveRecord::Validations::ClassMethods).

If you want to use the uniqueness validator, you can define the add_custom_validation as a class method as well and then you should be able to use it. Something like,

require 'active_support/concern'

module CommonValidator
  extend ActiveSupport::Concern

  included do
    add_custom_validation
  end

  class_methods do
    def add_custom_validation
      required_fields = get_required_fields # This will also need to be a class method now
      return if required_fields.blank?
      
      validates_uniqueness_of required_fields.map(&:to_sym)
    end
  end
end