LoginSignup
4
4

More than 5 years have passed since last update.

rails マイグレーションで dateのデフォルト値を設定する(postgres)

Posted at

環境

rails 4.2.4
postgres (PostgreSQL) 9.4.1

本題

date型のデフォルト値を設定したい場合、
1. データを格納するときにデフォルト値を入れる
2. sql文を実行する

の2つの方法がありますが、1だと入り口が複数あるときに漏れが生じ得ます。
sql文を発行しましょう

xxx_change_column_to_account.rb
class ChangeColumnToAccount < ActiveRecord::Migration
  def up
    execute "ALTER TABLE accounts ALTER COLUMN expired_at SET DEFAULT CURRENT_TIMESTAMP + interval '1day';"
  end

  def down
    execute "ALTER TABLE accounts ALTER COLUMN expired_at DROP DEFAULT;"
  end
end

もし全てのtableにdefault値を設定したい場合、次のようにするとtable名を配列で取得できます。

table_list.rb
def tables_except_schema_migrations
    ActiveRecord::Base.connection.tables.tap {|table| table.delete('schema_migrations') }
end

ちなみに、change_column :accounts, :expired_at, :date, default: (Time.now + 1.day) とやると
マイグレーション時に評価され、デフォルト値がいつも同じ日付になってしまいます。

4
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
4
4