如何在Rails 3中实现最小/最大validation器?

在Rails 3中实现最小validation器的方式是什么?

我有一个模型,min_age和max_age属性。

年龄可以在0..100的范围内,但是我也想validation交叉值,我的意思是max大于或等于min

{:min_age => 0, :max_age => 0} => true {:min_age => 0, :max_age => 1} => true {:min_age => 1, :max_age => 0} => false # max < min {:min_age => 1, :max_age => 101} => false # out of 0..100 range 

查看ActiveModel :: Validations :: NumericalityValidator: RailsAPI NumericalityValidator

规格:

 it { subject.max_age = 10 subject.min_age = 20 subject.should be_invalid subject.errors[:min_age].should include("must be less than or equal to #{subject.max_age}") } 

码:

 validates :min_age, numericality: { greater_than: 0, less_than_or_equal_to: :max_age } validates :max_age, numericality: { less_than_or_equal_to: 100 } 

我不知道你是否想要validation是否存在,但是你可以把它作为validation的另一个关键,例如

 validates :max_age, numericality: { less_than_or_equal_to: 100 }, presence: true 

你也可以使用包含… ,如:

 validates :height, :inclusion => { :in => 1..3000, :message => "The height must be between 1 and 3000" } 
 validates_numericality_of :min_age, greater_than: 0 validates_numericality_of :max_age, less_than_or_equal_to: 100 validates_numericality_of :max_age, greater_than: :min_age 

您也可以使用年龄,如下所示:

 validates_numericality_of :age, less_than_or_equal_to: 100, greater_than: 0