Programming in Paradise

Monday, January 23, 2006

HABTM and Migrations Gotcha

If you are using migrations in your Rails apps (and you should) and you are also using has-and-belongs-to-many relationships then there is a gotcha to be aware of. The join tables in a HABTM relationship should *not* include an ID column, however migrations, by default, creates ID columns from all of your tables. Therefore, to avoid this problem, all join tables in HABTM relationships should include :id => false in the create_table invocation.

Example:
create_table :people_pets, :id => false do |t|
t.column :person_id, :integer, :null => false
t.column :pet_id, :integer, :null => false
end
Good stuff to know.

2 Comments:

  • Thanks for writing about this; I was having duplicate ID problems and fixed it by manually deleting the ID column from the HABTM join table, but was puzzled that none of the HABTM pages said anything about omitting the ID column in the migration.

    By Blogger mike, at 6:00 AM  

  • *Very* good stuff to know.

    I couldn't figure out why the database table primary id kept mirroring that of the joined M:N table id.

    Thanks for the tip. Saved me quite a bit of grief.

    ciao !
    Daryl.

    By Anonymous Daryl, at 7:14 AM  

Post a Comment

Links to this post:

Create a Link

<< Home