Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.2 foreign key

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!

like image 524
TomDogg Avatar asked Nov 29 '14 10:11

TomDogg


1 Answers

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.

like image 171
Surya Avatar answered Sep 28 '22 01:09

Surya