O
O
Ord EO2021-08-19 13:39:00
Ruby on Rails
Ord EO, 2021-08-19 13:39:00

How to validate the time span in a rail model?

There is a simple rails application, there is a user model User, the user has a date_of_birth field
How to validate this field in the model to check that date_of_birth is in the range from 01/01/1900 to today, inclusive, despite the fact that this field may not be at all, but if there is, then it fits this range.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vayladion Gognazdiak, 2021-08-19
@OrdeO

class User < ApplicationRecord
  validates_with UserBirthZalupaValidator
end

class UserBirthZalupaValidator < ActiveModel::Validator
  def validate(record)
    begin
      birth = Date.parse(record.birth_date.to_s)
      record.errors.add(:base, "zlpa") unless birth.between?(start_date, end_date)
    rescue StandardError => e
      Rails.logger.error("Full zlpa: #{e.inspect}")
    end
  end

  def start_date
    Date.new(1900,1,1)
  end

  def end_date
    Time.zone.today
  end
end

More or less like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question