Let's assume I have a 2 models, "Programmer" and "Project", a programmer can work on many projects, and a project can have many programmers (obviously right?).
To do this in Rails, I took the following steps.
Generate the migration file
rails g migration CreateJoinTableProgrammerProject programmer project
class CreateJoinTableProgrammerProject < ActiveRecord::Migration def change create_join_table :programmers, :projects do |t| # t.index [:programmer_id, :project_id] # t.index [:project_id, :programmer_id] end end end
Uncomment the first line that create the index for [:programmer_id, :project_id]; this will let rails to add the index in the database (choosing the right index depend on how the data are query).
You'd also need to update the model classes to includes the necessary relations.
# models/programmer.rb class Programmer < ActiveRecord::Base has_and_belongs_to_many :projects end # models/project.rb class Project < ActiveRecord::Base has_and_belongs_to_many :programmers end
@project = programmer.projects.build(project_params) programmer.save