Madogiwa Blog

主に技術系の学習メモに使っていきます。

Ruby on Rails:過去日・未来日を判定する

Railsで過去日・未来日判定を行う際に下記のような実装をしていたのですが、便利なメソッドがRailsに用意されていたので、φ(..)メモメモ
Rubyでは使用出来ないので、注意してください(._.)

# 生年月日に未来日は設定不可
def birthday_cannot_be_in_the_future
  if birthday.present? && birthday > Date.today
    errors.add(:birthday, "can not specify your future date as your birth date.")
  end
end

# スケジュールに過去日は設定不可
def schedule_cannot_be_in_the_past
  if schedule.present? && schedule < Date.today
    errors.add(:schedule, "can not specify your past date as your schedule.")
  end
end

Railsには過去日の判定を行うDate.past?、未来日の判定を行うDate.future?があるので、><を使用するよりも綺麗に実装出来ます。

# 生年月日に未来日は設定不可
def birthday_cannot_be_in_the_future
  if birthday.present? && birthday.future?
    errors.add(:birthday, "can not specify your future date as your birth date.")
  end
end

# スケジュールに過去日は設定不可
def schedule_cannot_be_in_the_past
  if schedule.present? && schedule.past?
    errors.add(:schedule, "can not specify your past date as your schedule.")
  end
end

ちなみにDateTimeでも同様にfuture?past?が使えます(..)アリガタヤ

past? (DateTime) - APIdock

future? (DateTime) - APIdock

以上です。