Many To Many (through Pivot / Junction)
Preparing your DB schema
For defining many_to_many(m2m) relations you need to define aPivot(junction) table and a foreign_key / unique constraint(index).
Naming of the Pivot table requires models to be ordered alphabetically and in singular form. For instance a Pivot table between the models Tag and user should be named tag_user.
⭕
tag_user❌
user_tag -> Not ordered alphabetically❌
tag_users -> Not in singular form❌
tags_users -> Not in singular form
Let's define a User has_many Tags through "tag_user" pivot table (many_to_many) relation for example.
class AddUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
# "id" primary key column will also be added implicitly by Rails(ActiveRecord)
t.string :email, null: false
end
end
endclass AddTags < ActiveRecord::Migration[7.0]
def change
create_table :tags do |t|
t.string :label, null: false
end
# Use "label" as the primary key column
add_index :tags, :label, unique: true
end
endResulting Model Relations
With the DB setup above, EzQL will generate the following Model Relations.
Last updated

