13

我有一个非常通用的验证器,我想向它传递参数。

这是一个示例模型:

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

有没有办法根据验证的字段将参数传递给验证器?

谢谢

4

1 回答 1

22

我也不知道这一点,但是如果你想传递一个参数,那么将一个哈希传递给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

GenericValidator现在应该可以访问您要在验证中传递的两个参数:options[:order_type]options[:task_type].

然而,将它们分成两个验证器可能更有意义,它们都继承了dpassage提到的共享行为:

  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
于 2012-10-28T11:27:57.540 回答