How to validate the date such that it is after today in Rails?

后端 未结 5 565
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 19:07

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

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 19:09

    In rails 4+ there are future? and past? methods for DateTime objects, so a simpler answer is

    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.past?
          errors.add(:expiration_date, "can't be in the past")
        end
      end    
    end
    

提交回复
热议问题