[英]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::HelperMethods
和ActiveRecord::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.