Create migration - create a connection table

I looked through many SO and google posts to generate a connection table migration for the has many and belongs to many association and nothing works.

All solutions generate an empty migration file.

I am using rails 3.2.13 and I have two tables: security_users and assignments . Here are some of my attempts:

 rails generate migration assignments_security_users rails generate migration create_assignments_security_users rails generate migration create_assignments_security_users_join_table rails g migration create_join_table :products, :categories (following the official documentation) rails generate migration security_users_assignments security_user:belongs_to assignments:belongs_to 

Can anyone tell how to create a join table migration between two tables?

+51
ruby-on-rails ruby-on-rails-3 migration ruby-on-rails-4 jointable
Jul 20 '13 at 18:18
source share
3 answers

Run this command to generate an empty migration file (it does not fill out automatically, you need to fill it yourself):

 rails generate migration assignments_security_users 

Open the created migration file and add this code:

 class AssignmentsSecurityUsers < ActiveRecord::Migration def change create_table :assignments_security_users, :id => false do |t| t.integer :assignment_id t.integer :security_user_id end end end 

Then run rake db:migrate from your terminal. I created a many_to_many relationship quiz with a simple example that could help you.

+35
Jul 20 '13 at 19:12
source share

To autopopulate the create_join_table command on the command line, it should look like this:

 rails g migration CreateJoinTableProductsSuppliers products suppliers 

For product model and vendor model. Rails will create a table called "products_suppliers". Pay attention to pluralization.

(Note that the generation command can be shortened to g )

+128
Dec 19 '13 at 3:16
source share

I usually like to have a β€œmodel” file when I create a connection table. Therefore, I do.

 rails g model AssignmentSecurityUser assignments_security:references user:references 
+14
Jul 28 '16 at 10:51
source share



All Articles