Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate migration - create join table

I have looked through many SO and google 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: security_users and assignments. 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?

like image 881
gotqn Avatar asked Jul 20 '13 18:07

gotqn


People also ask

How is schema RB generated?

It is a Ruby representation of your database; schema. rb is created by inspecting the database and expressing its structure using Ruby.

What is migration in Ruby on rails?

Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database.


2 Answers

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

rails g migration CreateJoinTableProductsSuppliers products suppliers 

For a Product model and a Supplier model. Rails will create a table titled "products_suppliers". Note the pluralization.

(Side note that generation command can be shortened to just g)

like image 190
andrewcockerham Avatar answered Sep 22 '22 16:09

andrewcockerham


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     end   end end 

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.

like image 37
Powers Avatar answered Sep 22 '22 16:09

Powers