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]

ただし、これらを2つのバリデーターに分割し、両方とも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 に答える