Rails 4.2 foreign key

2019-06-17 02:11发布

Rails 4.2 newly supports adding and removing foreign keys (in migrations), like:

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

What I don't understand is: How is this

add_foreign_key :articles, :authors

different from this:

add_column :articles, :author_id, :integer

Thank you for any clarification!

1条回答
小情绪 Triste *
2楼-- · 2019-06-17 02:49

The difference is that line:

add_foreign_key :articles, :authors

will actually generates this:

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

While this:

add_column :articles, :author_id, :integer

will generate:

ALTER TABLE "articles" ADD COLUMN author_id INT(11);

Both are different because add_foreign_key will add just a foreign key constraint, while add_column adds a column not a constraint.

查看更多
登录 后发表回答