Create a Join Table using Migrations
suggest changeA has_and_belongs_to_many association needs a join table. You can create it with create_table. Suppose the models are Tag and Project:
class CreateProjectsTagsJoinTableMigration < ActiveRecord::Migration
def change
create_table :projects_tags, id: false do |t|
t.integer :project_id
t.integer :tag_id
end
end
end
The table name puts the plural names in alphabetical order. projects comes before tags, so the table is projects_tags.
The table only connects the two models, so it does not need its own primary key. Pass id: false.
The table name is the plural of both models. Each foreign-key column is singular: project_id and tag_id. Add a unique index on those two columns so the same pair cannot be stored twice.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents