gotqn gotqn - 1 year ago 118
Ruby Question

Generate migration - create join table

I have looked through many

posts for generating migration of join table for
has many and belongs to many
association and nothing work.

All of the solutions are generating a empty migration file.

I am using
rails 3.2.13
and I have two tables:
. These are some of things I have try:

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?

Answer Source

Run this command to generate the empty migration file (it is not automatically populated, you need to populate it yourself):

rails generate migration assignments_security_users

Open up the generated 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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download