Rails 4.2 foreign key

白昼怎懂夜的黑 提交于 2019-12-08 19:37:43

问题


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:


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.



来源:https://stackoverflow.com/questions/27201054/rails-4-2-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!