Today I Learned Create a join table in a Rails migration

Rails has a handy create_join_table migration helper for has_and_belongs_to_many relationships. This automatically sets up the relationship table, sets id: false, adds the references, and follows the conventions needed to make has_and_belongs_to_many work without extra configuration.

create_join_table :articles, :tags

The create_join_table method can optionally be passed a block, which allows you to extend the created table. This is handy for adding a unique index.

create_join_table :articles, :tags do |t|
  t.index :article_id
  t.index :tag_id
  t.index [:article_id, :tag_id], unique: true,
end

One gotcha to be aware of: create_join_table doesn’t automatically foreign key constraints or reference indices. You have to do that yourself.

add_foreign_key :articles_tags, :articles
add_foreign_key :articles_tags, :tags