簡體   English   中英

為 Rails 中的動態屬性添加唯一性驗證

[英]Adding uniqueness validation for dynamic attributes in rails

我們有一個多租戶應用程序,其中每個帳戶的驗證都不同。 我們可以很容易地實現這一點,如下所示,

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

然后我們必須添加基於帳戶的唯一性驗證,所以嘗試相同。 但得到未定義的方法錯誤。 有什么辦法可以讓我完成這項工作嗎?

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實際上是一個 class 方法(在ActiveRecord::Validations::ClassMethods中定義),因此您無法從 ZA8CFDE6331BD59EB2AC96F8911ZC4 的上下文中調用它。

validates_presence_of既是一個輔助方法,也是一個 class 方法(在ActiveModel::Validations::HelperMethodsActiveRecord::Validations::ClassMethods )。

如果您想使用唯一性驗證器,您也可以將add_custom_validation定義為 class 方法,然后您應該可以使用它。 就像是,

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