简体   繁体   English

为 Rails 中的动态属性添加唯一性验证

[英]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. validates_uniqueness_of实际上是一个 class 方法(在ActiveRecord::Validations::ClassMethods中定义),因此您无法从 ZA8CFDE6331BD59EB2AC96F8911ZC4 的上下文中调用它。

Whereas validates_presence_of is both a helper method, and a class method (defined in ActiveModel::Validations::HelperMethods and ActiveRecord::Validations::ClassMethods ).validates_presence_of既是一个辅助方法,也是一个 class 方法(在ActiveModel::Validations::HelperMethodsActiveRecord::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.如果您想使用唯一性验证器,您也可以将add_custom_validation定义为 class 方法,然后您应该可以使用它。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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