Rails: Join model table migration template

Posted . Visible to the public.

When creating a database table for a join model, you can use this template. For models Student and School:

class CreateStudentSchools < ActiveRecord::Migration[7.2]
  def change
    create_table :student_schools do |t|
      t.timestamps

      t.references :student, null: false, foreign_key: true
      t.references :school, null: false, foreign_key: true
      
      t.index [:student_id, :school_id], unique: true
    end
  end
end

It sets a few database constraints that ensure data integrity:

  • null: false: Prevent join records without associations.
  • foreign_key: true: Prevent deleting a joined record. Set dependent: :destroy on your has_many :student_schools association in both models to remove join records together with the model records.
  • Index: Prevent duplicate join records.
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2025-11-27 06:56)