Rails验证动态包含

时间:2012-01-23 14:00:37

标签: ruby-on-rails ruby validation

class A
  include ActiveModel::Validations
  attr_reader :operator
  def initialize(operator)
    @operator = operator
    validates_inclusion_of :operator, in => operators
  end

  def operators
    ....
  end
end

这里我想动态验证operator_of的运算符。方法运算符返回一个动态的运算符数组。

以上代码无效。如何动态实现验证? [R

1 个答案:

答案 0 :(得分:3)

您可以尝试:

def initialize(operator)
  self.class.class_eval do
    validates_inclusion_of :operator, :in => operators
  end
end

虽然我不明白为什么你不能在课堂上定义它。请注意,参数:in可以是lambda,有关详细信息,请参阅:http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of