Ruby on rails 3 Rails/ActiveModel将参数传递给每个验证器

Ruby on rails 3 Rails/ActiveModel将参数传递给每个验证器,ruby-on-rails-3,validation,mongoid,aggregation,activemodel,Ruby On Rails 3,Validation,Mongoid,Aggregation,Activemodel,我有一个非常通用的验证器,我想把它传递给其他参数 以下是一个示例模型: class User include Mongoid::Document field :order_type has_many :orders, inverse_of :user validates: orders, generic: true #i want to pass argument (order_type) field :task_type has_many :tasks, inver

我有一个非常通用的验证器,我想把它传递给其他参数

以下是一个示例模型:

class User
  include Mongoid::Document

  field :order_type
  has_many :orders, inverse_of :user
  validates: orders, generic: true #i want to pass argument (order_type)

  field :task_type
  has_many :tasks, inverse_of :user
  validates: tasks, generic: true #i want to pass argument (task_type)
end
和示例验证程序:

class GenericValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    if some_validation?(object)
      object.errors[attribute] << (options[:message] || "is not formatted properly") 
    end
  end
end
class GenericValidatorobject.errors[attribute]我也没有意识到这一点,但是如果您想传递一个参数,那么将哈希传递给
generic:
,而不是
true
。详细说明您希望遵循的确切流程:

class User
  include Mongoid::Document

  field :order_type
  has_many :orders, inverse_of :user
  validates: orders, generic: { :order_type => order_type }

  field :task_type
  has_many :tasks, inverse_of :user
  validates: tasks, generic: { :task_type => task_type }
end
genericvalidater
现在应该可以访问要在验证中传递的两个参数:
options[:order\u type]
options[:task\u type]

但是,将它们分成两个验证器可能更有意义,两个验证器都继承了以下所述的共享行为:


你这样做的目的是什么?考虑到Rails API,这并不是实现这一点的最佳方法。在我的原始代码中,我想找出我的模型中是否存在循环依赖关系。模型A有许多模型B。模型B有一个模型A。我想验证从模型A到模型本身没有循环。问题是,我有两种不同的关系需要验证循环,它们之间的验证器差别非常小。我想看看我是否可以一般地通过传递哪些字段来搜索周期,而不是重写相同的周期逻辑和验证器。我想你最好使用子类化来实现这一点,而不是参数化。我现在使用子类,但是我仍然感兴趣的是参数是否可以通过验证器传递。在我的代码中还有其他地方我可以使用这个能力,我只是好奇
  class User
    include Mongoid::Document

    field :order_type
    has_many :orders, inverse_of :user
    validates: orders, order: { type: order_type }

    field :task_type
    has_many :tasks, inverse_of :user
    validates: tasks, task: { type: task_type }
  end