Rails / ActiveModel将参数传递给EachValidator

时间:2012-10-24 01:59:03

标签: 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, 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

有没有办法将参数传递给验证器,具体取决于验证哪个字段?

感谢

1 个答案:

答案 0 :(得分:17)

我也没有意识到这一点,但是如果你想传递一个参数,那么将哈希值传递给generic:而不是trueThis post详细说明了您想要遵循的具体过程:

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