Create join table migration in Rails
3 April 2022 (Updated 3 April 2022)
Suppose you want to create a quotes_tags
join table with two foreign keys:
quote_id
: foreign key ofquotes.id
tag_id
: foreign key oftags.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
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment