When attempting to use
has_and_belongs_to_many you might run into a “relation does not exist” error. If you created a join table migration already, and you’re wondering why ActiveRecord isn’t looking at it, you probably used the wrong table name.
Creating Join Relations Correctly
When looking up a
habtm join table, ActiveRecord arranges the model names in alphabetical order. So a
habtm join table for the models
People should have a table name of
clubs_people. The migration should look like this:
Just as a reference for the future, you should also notice a few more things about this:
:id => falseWhen I create a join table, I don’t need an extra ID field hanging around. I will never be looking up a join by its id, so including an ID is wasteful. This does create a small problem, however: ActiveRecord will not create a default Primary Key, so you will have to create it yourself.
t.referencesInstead of using
t.integer, I use
t.referencesbecause it will automatically link to the default Primary Key on the table names it is given in symbol form.
add_index...:unique => trueI add an index between the two fields for faster recall from the database. I make the index unique because a record in Table A should not be associated with a record in Table B more than once in a join table in most circumstances.
Fixing Already Migrated Relations
The above doesn’t help if you’ve already created your table, but the solution is very simple: