Rails 4.2 foreign key

Rails 4.2 again supports adding and removing foreign keys (in migrations), for example:

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

I do not understand: how is it

 add_foreign_key :articles, :authors 

different from this:

 add_column :articles, :author_id, :integer 

Thanks for any clarification!

+7
ruby-on-rails migration ruby-on-rails-4 foreign-keys
source share
1 answer

The difference is that the line:

 add_foreign_key :articles, :authors 

actually generates this:

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

So far it is:

 add_column :articles, :author_id, :integer 

will generate:

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

Both are different from each other because add_foreign_key will only add a foreign key constraint , and add_column add a non-constraint column.

+9
source share

All Articles