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. Setdependent: :destroyon yourhas_many :student_schoolsassociation in both models to remove join records together with the model records. - Index: Prevent duplicate join records.
Posted by Dominik Schöler to makandra dev (2025-11-27 06:56)