Add nullable foreign key in Rails

后端 未结 3 1028
孤街浪徒
孤街浪徒 2020-12-13 17:40

Referencing to Rails 4.2 add_foreign_key support:

    # add a foreign key to `articles.author_id` referencing `authors.id`
    add_foreign_key :articles, :au         


        
3条回答
  •  無奈伤痛
    2020-12-13 17:49

    There is nothing in the guide that implies add_foreign_key would make the corresponding foreign field "NOT NULL" or required. add_foreign_key simply adds a foreign key constraint whether the field is required or not (in your case author_id in articles).

    Did you get an error when you tried this in your migration?

    Here's the SQL that it would generate:

    ALTER TABLE "articles" ADD CONSTRAINT articles_author_id_fk FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
    

    SO, if in your original migration of articles, author_id is null, then you can have foreign key that's nullable.

提交回复
热议问题