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

后端 未结 5 572
伪装坚强ぢ
伪装坚强ぢ 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:10

    I took @dankohn answer, and updated to be I18n ready. I also removed the blank test, because that's not the responsibility of this validator, and can easily be enabled by adding presence: true to the validates call.

    The updated class, now named in_future, which I think is nicer than not_in_past

    class InFutureValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors.add(attribute, (options[:message] || :in_future)) unless in_future?(value)
      end
    
      def in_future?(date)
        date.present? && date > Time.zone.today
      end
    end
    

    Now add the in_future key to your localization file.

    For all fields under errors.messages.in_future, e.g. for Dutch:

    nl:
      errors:
        messages:
          in_future: 'moet in de toekomst zijn'
    

    Or per field under activerecord.errors.models.MODEL.attributes.FIELD.in_future, e.g. for the end_date in a Vacancy model in Dutch:

    nl:
      activerecord:
        errors:
          models:
            vacancy:
              attributes:
                end_date:
                  in_future: 'moet in de toekomst zijn'
    

提交回复
热议问题