aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorVipul A M <vipulnsward@gmail.com>2017-03-07 18:45:35 +0530
committerGitHub <noreply@github.com>2017-03-07 18:45:35 +0530
commit355a2fcfe9d76ece068d2df7b51fe71863cb9e51 (patch)
tree81c0450cb9f111a62a93fa66ab2d1cae23734374
parent9b84567fd438acf0e4a973e2be46dce3ba5c6ea0 (diff)
parente1567d0d3a3c0ae1f4da1fb8b5b77a85767fb6ae (diff)
downloadrails-355a2fcfe9d76ece068d2df7b51fe71863cb9e51.tar.gz
rails-355a2fcfe9d76ece068d2df7b51fe71863cb9e51.tar.bz2
rails-355a2fcfe9d76ece068d2df7b51fe71863cb9e51.zip
Merge pull request #28289 from maicher/master
Improve foreign key description in guides
-rw-r--r--guides/source/association_basics.md20
1 files changed, 18 insertions, 2 deletions
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index 73c9c10c1f..5794bfa666 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -582,14 +582,30 @@ class CreateBooks < ActiveRecord::Migration[5.0]
t.string :book_number
t.integer :author_id
end
-
- add_index :books, :author_id
end
end
```
If you create an association some time after you build the underlying model, you need to remember to create an `add_column` migration to provide the necessary foreign key.
+It's a good practice to add an index on the foreign key to improve queries
+performance and a foreign key constraint to ensure referential data integrity:
+
+```ruby
+class CreateBooks < ActiveRecord::Migration[5.0]
+ def change
+ create_table :books do |t|
+ t.datetime :published_at
+ t.string :book_number
+ t.integer :author_id
+ end
+
+ add_index :books, :author_id
+ add_foreign_key :books, :authors
+ end
+end
+```
+
#### Creating Join Tables for `has_and_belongs_to_many` Associations
If you create a `has_and_belongs_to_many` association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the `:join_table` option, Active Record creates the name by using the lexical book of the class names. So a join between author and book models will give the default join table name of "authors_books" because "a" outranks "b" in lexical ordering.