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).

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
end
class 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
end

Resulting Model Relations

With the DB setup above, EzQL will generate the following Model Relations.

Last updated