sajad torkamani

Suppose you want to create a quotes_tags join table with two foreign keys:

  • quote_id: foreign key of quotes.id
  • tag_id: foreign key of tags.id

You can do this with:

r g migration CreateJoinTableQuotesTag

Update the generated migration file to the following:

# frozen_string_literal: true

class CreateJoinTableQuotesTags < ActiveRecord::Migration[7.0]
  def change
    create_table :quotes_tags, id: false do |t|
      t.references :quote, null: false, foreign_key: true
      t.references :tag, null: false, foreign_key: true
      t.timestamps

      t.index [:quote_id, :tag_id], unique: true
    end
  end
end
Tagged: Rails

Leave a comment

Your email address will not be published. Required fields are marked *