class A
include ActiveModel::Validations
attr_reader :operator
def initialize(operator)
@operator = operator
validates_inclusion_of :operator, in => operators
end
def operators
....
end
end
在这里,我想动态验证 inclusion_of 运算符。方法运算符返回一个动态的运算符数组。
以上代码无效。如何动态实现验证? r
最佳答案
你可以试试:
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
关于ruby-on-rails - Rails 验证包含动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972807/