LoginSignup
21
16

More than 3 years have passed since last update.

migration の timestamps で作成するカラムを NOT NULL にする

Last updated at Posted at 2014-03-12

2020/01/08 追記: Rails 5 で t.timestamps で作成するカラムはデフォルトで NOT NULL になったため、こちらの対応は不要になりました。

マイグレーションで created_atupdated_at を定義する時に t.timestamps と書くことが多いと思うけれど、普通にマイグレーションを流すと NULL 可になる。

Rails に任せておけば NULL が入ることはないと思うが、NOT NULL にしておきたい。

migration でこう書く:

t.timestamps には引数を渡せる。

def change
  create_table :posts do |t|
    t.string :title, null: false

    t.timestamps null: false
  end
end

db:migrate すると schema.rb はこうなる:

create_table "posts", force: true do |t|
  t.string   "title",      null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

PostgreSQL で確認:

test=> \d posts;                                                           
                                        Table "public.posts"                                         
     Column      |            Type             |                       Modifiers                        
-----------------+-----------------------------+------------------------------------------------------- 
 id              | integer                     | not null default nextval('posts_id_seq'::regclass)  
 title           | character varying(255)      | not null                                               
 created_at      | timestamp without time zone | not null                                               
 updated_at      | timestamp without time zone | not null                                               

殆どの場面ではこれらのカラムは NOT NULL になって良いと思うのだけれど、何か罠があるのだろうか。外部キー制約も Foreigner を使わないと定義できないし、勝手にやれってことなのかな。

21
16
2

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
21
16