多字段/范围验证 [英] Multifield/range validation

查看:30
本文介绍了多字段/范围验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何验证模型的一个字段与另一个字段相比更小"?

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

这篇关于多字段/范围验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆