Skip to content

Instantly share code, notes, and snippets.

@abuiles
Created December 3, 2009 22:05
Show Gist options
  • Save abuiles/248585 to your computer and use it in GitHub Desktop.
Save abuiles/248585 to your computer and use it in GitHub Desktop.
Rails assumes that a join table is named after the two tables it joins (with the
names in alphabetical order). Rails will automatically find the join table cat-
egories_products linking categories and products. If you used some other name,
you’ll need to add a :foreign_key declaration so Rails can find it. We describe
this in Section 19.3, belongs_to and has_xxx Declarations, on page 362.
Note that our join table does not need an id column for a primary key, because
the combination of product and category id is unique. We stopped the migra-
tion from automatically adding the id column by specifying :id => false. We then
created two indices on the join table. The first, composite index actually serves
two purposes: it creates an index that can be searched on both foreign key
columns, and with most databases it also creates an index that enables fast
lookup by the product id. The second index then completes the picture, allow-
ing fast lookup on category id.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment