ActiveRecord Migrations for Has And Belongs To Many Relationships

I just stumbled upon this small gotcha when working with ActiveRecord migrations to create a join table for a Has And Belongs To Many (HABTM) relationship. By default the create_table will always add an id column (as the primary key). This behaviour is bad for HABTM join tables, the documentation points out how to rectify the problem.

Do not add a primary key column

 create_table(:categories_suppliers, :id => false) do |t|
   t.column :category_id, :integer
   t.column :supplier_id, :integer
 end

This will create the join table with the desired 2 columns; category_id and supplier_id only. You will probably want to add an index to both of these columns as well.

add_index :categories_suppliers, [:category_id, :supplier_id], :unique => true

About this entry