add_foreign_key
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1 (0)
- 4.2.7 (5)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (9)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (38)
- 7.1.3.2 (34)
- 7.1.3.4 (0)
- What's this?
add_foreign_key(from_table, to_table, options = {})
public
Adds a new foreign key. from_table is the table with the key column, to_table contains the referenced primary key.
The foreign key will be named after the following pattern: fk_rails_<identifier>. identifier is a 10 character long string which is deterministically generated from the from_table and column. A custom name can be specified with the :name option.
Creating a simple foreign key
add_foreign_key :articles, :authors
generates:
ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
Creating a foreign key on a specific column
add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id"
generates:
ALTER TABLE "articles" ADD CONSTRAINT fk_rails_58ca3d3a82 FOREIGN KEY ("author_id") REFERENCES "users" ("lng_id")
Creating a cascading foreign key
add_foreign_key :articles, :authors, on_delete: :cascade
generates:
ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON DELETE CASCADE
The options hash can include the following keys:
- :column
-
The foreign key column name on from_table. Defaults to to_table.singularize + "_id"
- :primary_key
-
The primary key column name on to_table. Defaults to id.
- :name
-
The constraint name. Defaults to fk_rails_<identifier>.
- :on_delete
-
Action that happens ON DELETE. Valid values are :nullify, :cascade and :restrict
- :on_update
-
Action that happens ON UPDATE. Valid values are :nullify, :cascade and :restrict
- :validate
-
(PostgreSQL only) Specify whether or not the constraint should be validated. Defaults to true.
Default values
By default :on_update and :on_delete have :restrict value.