1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】マイグレーションでDATE型のデフォルトを現在日時にする

Last updated at Posted at 2021-09-23

レコードが作成された日時をデフォルトにカラムが作成されるようにしたい。
DATETIME型で現在日時をデフォルトに入力する方法は多々見つかったものの、DATE型については情報があまり見つからなかったのでメモする。

DATE型で現在の日時をデフォルトにする

migration

t.date :date, null: false, default: -> { '(CURRENT_DATE)' }

()を忘れずに!!

確認

mysql> show columns from テーブル名 like "date";
+---------+------+------+-----+------------------+-------------------+
| Field   | Type | Null | Key | Default          | Extra             |
+---------+------+------+-----+------------------+-------------------+
| date    | date | NO   |     | (curdate())      | DEFAULT_GENERATED |
+---------+------+------+-----+------------------+-------------------+

おまけ

現在から5日後をデフォルトにする

migration
t.date :date, default: -> { '(CURRENT_DATE + INTERVAL 5 DAY)' }
確認
mysql> show columns from テーブル名 like "date";
+---------+------+------+-----+------------------------------+-------------------+
| Field   | Type | Null | Key | Default                      | Extra             |
+---------+------+------+-----+------------------------------+-------------------+
| date    | date | NO   |     | (curdate() + interval 5 day) | DEFAULT_GENERATED |
+---------+------+------+-----+------------------------------+-------------------+

NG記法

t.date :date, default: Time.now.to_date

レコード作成時ではなく、Time.now.to_date= テーブル作成時の日付をデフォルトに設定されてしまう。


DATETIME型で現在時刻をデフォルトにする

t.datetime :update_date, default: -> { 'NOW()' }

環境

  • Rails 6.1.4
  • mysql:8.0
1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?