LoginSignup
2
1

More than 3 years have passed since last update.

Rails 日付カラムのバリデーション設定

Posted at

はじめに

Railsを使ってオリジナルアプリを開発しています。日付カラムに今日の日付より後(明日以降)は保存できないように、バリデーションを設定しました。忘れないように書き記します。

目次

1.日付カラムのバリデーション
2.モデルへの追加記述

1.日付カラムのバリデーション

今回suggestionテーブルにlast_cleaned_dateカラム(最後に掃除した日付)を作成した。下記のように空の場合、保存できないバリデーションは設定した。しかし、他カラムと異なり、空以外のバリデーションは別で行う必要がある。

app/models/suggestion
class Suggestion < ApplicationRecord
  with_options presence: true do
#----------------中略-------------------    
    validates :last_cleaned_date #←対象のカラム
  end
  belongs_to :user
end

2.モデルへの追加記述

同ファイルにバリデーションを追記する。ここではlast_cleaned_dateカラムが空でなかった場合、day_after_todayの処理が行われる。errors.addでエラーの種類を追加する。ここでもif文で条件を定義した。last_cleaned_dateが今日の日付(Date.today)より大きい場合、明日以降を示す。そして条件を満たした場合、保存されずエラーを表示する。

app/models/suggestion.rb
validate :day_after_today
  def day_after_today
    unless last_cleaned_date == nil
      errors.add(:last_cleaned_date, 'は、今日を含む過去の日付を入力して下さい') if last_cleaned_date > Date.today
    end
  end

参考までに実装後のエラー表示画面を下記に示す。本日の日付(2020/11/19)で保存しようとした場合の、エラー文である。

image.png

以上

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1