I have two models restaurant
and user
that I want to perform a has_and_belongs_to_many relationship.
I have already gone into the model files and added the has_and_belongs_to_many :restaurants
and has_and_belongs_to_many :users
I assume at this point I should be able to do something like with Rails 3:
rails generate migration ....
but everything I have tried seems to fail. I'm sure this is something really simple I'm new to rails so I'm still learning.
When creating the join table, pay careful attention to the requirement that the two tables need to be listed in alphabetical order in the migration name/class. This can easily bite you if your model names are similar, e.g. "abc" and "abb". If you were to run
Your relations will not work as expected. You must use
instead.
For HABTM relationships, you need to create a join table. There is only join table and that table should not have an id column. Try this migration.
You must check this relationship rails guide tutorials
You need to add a separate join table with only a
restaurant_id
anduser_id
(no primary key), in alphabetical order.First run your migrations, then edit the generated migration file.
Rails 3
Rails 4:
Rails 5
From the docs:
Your migration file (note the
:id => false
; it's what prevents the creation of a primary key):Rails 3
Rails 4
t.belongs_to
will automatically create the necessary indices.def change
will auto detect a forward or rollback migration, no need for up/down.Rails 5
Note: There is also an option for a custom table name that can be passed as a parameter to create_join_table called
table_name
. From the docsThe answers here are quite dated. As of Rails 4.0.2, your migrations make use of
create_join_table
.To create the migration, run:
This will generate the following:
If you want to index these columns, uncomment the respective lines and you're good to go!