本文介绍了多字段/范围验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何验证模型的一个字段与另一个字段相比更小"?
how would I validate that one field of my Model is "smaller" compared to another?
class Event < ActiveRecord::Base validates :start, :presence => true validates :stop, :presence => true end此外 - 我如何确保两个值之间的差异"不超过最大范围?
In addition - how could I make sure that the "difference" between the two values doesn't exceed a maximum range?
干杯
推荐答案我有一个与此类似的验证,以确保学年在结束之前开始并且不超过一年.
I have a validation that's similar to this to make sure school years begin before they end and are not longer than a year.
validate :beginning_before_ending, :not_longer_than_year def beginning_before_ending errors.add(:base, 'Beginning date must be before ending date') if self.beginning > self.ending end def not_longer_than_year errors.add(:base, 'School year is too long') if self.beginning + 1.year < self.ending end所以你可以做这样的事情.
So you could do something like this.
validate :start_before_stop, :not_longer_than_whatever def start_before_stop errors.add(:base, 'Start must be before stop') if self.start > self.stop end def not_longer_than_whatever errors.add(:base, 'Range is too long') if self.start + whatever < self.stop end更多推荐
多字段/范围验证
发布评论