简体   繁体   中英

Adding uniqueness validation for dynamic attributes in rails

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM