ruby-on-railsmigrationcode-generationhas-and-belongs-to-many

Rails migration for has_and_belongs_to_many join table


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.


Solution

  • This HABTM section of the Associations Rails Guide is great, but doesn't explain exactly how to create a join table.

    However, the Migrations Rails Guide explains how to make a join table:

    The migration method create_join_table creates an HABTM (has and belongs to many) join table. A typical use would be:

    create_join_table :products, :categories

    By default, the name of the join table comes from the union of the first two arguments provided to create_join_table, in alphabetical order.