未来日・過去日の判定(カスタムvalidation)
class Record < ApplicationRecord ... validate :cannot_be_in_the_future ... # 日付に未来日は設定不可 def cannot_be_in_the_future if date.present? && date > Date.today errors.add(:date, :cannot_be_future_date) end end # 日付に過去日は設定不可 def cannot_be_in_the_past if date.present? && date < Date.today errors.add(:date, :cannot_be_past_date) end end end
これでも良いが、rails側に未来日を判定する Date.future?、過去日を判定する Date.past? があるので、これの方がわかりやすい。
class Record < ApplicationRecord ... validate :cannot_be_in_the_future validate :cannot_be_in_the_past ... # 日付に未来日は設定不可 def cannot_be_in_the_future if date.present? && date.future? errors.add(:date, :cannot_be_future_date) end end # 日付に過去日は設定不可 def cannot_be_in_the_past if date.present? && date.past? errors.add(:date, :cannot_be_past_date) end end end
このままだと英語がそのまま表示されてしまうので、ja.yml に対応する日本語を登録する。
# config/locales/ja.yml ja: activerecord: errors: models: record: attributes: date: cannot_be_future_date: "未来の日付は記録できません。" cannot_be_past_date: "過去の日付は記録できません。"
参考記事:
Ruby on Rails:過去日・未来日を判定する - Madogiwa Blog
Ruby on Rails:モデルに独自のバリデーションを実装する - Madogiwa Blog