Rails migration for has_and_belongs_to_many join table

ma11hew28 picture ma11hew28 · Dec 7, 2010 · Viewed 65.2k times · Source

How do I do a script/generate migration to create a join table for a has_and_belongs_to_many relationship?

The application runs on Rails 2.3.2, but I also have Rails 3.0.3 installed.

Answer

dangerousdave picture dangerousdave · May 7, 2011

Where:

class Teacher < ActiveRecord::Base
  has_and_belongs_to_many :students
end

and

class Student < ActiveRecord::Base
  has_and_belongs_to_many :teachers
end

for rails 4:

rails generate migration CreateJoinTableStudentTeacher student teacher

for rails 3:

rails generate migration students_teachers student_id:integer teacher_id:integer

for rails < 3

script/generate migration students_teachers student_id:integer teacher_id:integer

(note the table name lists both join tables in alphabetical order)

and then for rails 3 and below only, you need to edit your generated migration so an id field is not created:

create_table :students_teachers, :id => false do |t|