动态validates_length_of

我想尝试执行validates_length_of,但在运行时指定范围/最小值/最大值。

例如,我们有一个父模型:

class Parent < ActiveRecord::Base has_many :children # with attributes min_length, max_length end 

还有一个儿童模特:

 class Child < ActiveRecord::Base belongs_to :parent # with an attribute reference end 

那么我想在Child课程中做的是:

 validate :reference_length def reference_length options = { :within => parent.min_length..parent.max_length } self.class.validates_length_of :reference, options end 

但它不起作用,有没有办法做到这一点,而不做errors.add(:reference, message) if...

使用lambda函数可能有效:

 validates_length_of :reference, :minimum => lambda{parent.min_length}, :maximum => lambda{parent.max_length}