Home > Blockchain >  How to manage dates in Custom Validations in Rails
How to manage dates in Custom Validations in Rails

Time:08-03

Hello Devs I'm trying to compare dates in a custom validator, but it seems that i'm not doing it properly.

i need to make a condition for a document, if 90 days have passed since the date of expiration, if its true then return an error.

class CheckDocumentValidator < ActiveModel::Validator
    def validate(record)
        
        expiration_date = record.expiration_date
        actual_date = Time.current

        diff = ((actual_date - expiration_date.to_time)/3600).round

        days_diff = diff/24

        if days_diff > 90
           record.errors.add(:expiration_date, "error")
        end
    end
end

expiration_date is a date attribute on my model AttachmentInstance

In the logs says that -- Error: undefined method `to_time' for nil:NilClass

CodePudding user response:

i think the error

Error: undefined method `to_time' for nil:NilClass

is because no data found on record.expiration_date.

if record.expiration_date is Time class. it should be like this

if record.expiration_date   90.day > Time.now
 record.errors.add(:expiration_date, "error")
end
  • Related