Rails 4.2外键

时间:2014-11-29 10:05:31

标签: ruby-on-rails ruby-on-rails-4 foreign-keys migration

Rails 4.2新增支持添加和删除外键(在迁移中),例如:

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

我不明白的是:这是怎么回事?

add_foreign_key :articles, :authors

与此不同:

add_column :articles, :author_id, :integer

感谢您的任何澄清!

1 个答案:

答案 0 :(得分:9)

不同之处在于:

add_foreign_key :articles, :authors

实际上会生成这个:

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

虽然这个:

add_column :articles, :author_id, :integer

将生成:

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

两者都不同,因为add_foreign_key只会添加foreign key约束,而add_column会添加列而不是约束。