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
validates_uniqueness_of
is actually a class method (defined inActiveRecord::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 inActiveModel::Validations::HelperMethods
andActiveRecord::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,