如何在 Rails 中验证日期在今天之后? [英] How to validate the date such that it is after today in Rails?

查看:69
本文介绍了如何在 Rails 中验证日期在今天之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含属性的 Active Record 模型:expiry_date.我如何验证它是在今天之后(当时的当前日期)?我是 Rails 和 ruby​​ 的新手,我找不到类似的问题来回答这个问题?

I have an Active Record model that contains attributes: expiry_date. How do I go about validating it such that it is after today(present date at that time)? I am totally new to Rails and ruby and I couldn't find a similar question answering exactly this?

我使用的是 Rails 3.1.3 和 ruby​​ 1.8.7

I am using Rails 3.1.3 and ruby 1.8.7

推荐答案

您的问题(几乎)得到了准确解答 在 Rails 指南中.

Your question is (almost) exactly answered in the Rails guides.

这是他们提供的示例代码.这个类验证日期在过去,而您的问题是如何验证日期在未来,但调整它应该很容易:>

Here's the example code they give. This class validates that the date is in the past, while your question is how to validate that the date is in the future, but adapting it should be pretty easy:

class Invoice < ActiveRecord::Base
  validate :expiration_date_cannot_be_in_the_past

  def expiration_date_cannot_be_in_the_past
    if expiration_date.present? && expiration_date < Date.today
      errors.add(:expiration_date, "can't be in the past")
    end
  end    
end

这篇关于如何在 Rails 中验证日期在今天之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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