Generate migration - create join table - ruby-on-rails

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?

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)

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.

I usually like to have the "model" file as well when I create the join table. Therefore I do.
rails g model AssignmentSecurityUser assignments_security:references user:references

There's embeded generation for join table in rails
rails g migration AddCityWorkerJoinTable cities:uniq workers
which generates following migration
create_join_table :cities, :workers do |t|
t.index [:city_id, :worker_id], unique: true
end
❗️ NOTE:
models names should go in alphabet order
put :uniq only on first param

I believe this would be an updated answer for rails 5
create_table :join_table_name do |t|
t.references :table_name, foreign_key: true
t.references :other_table_name, foreign_key: true
end

Related

create a new table with one-to-many relationshiop

I have an old rails project using Rails 2 . There is already model class Student. In database, there is a table students. Now, I need to implement that each student can have multiple courses. Which means I need to have a new table in database that's courses table & have one-to-many relationship from student to course.
How to create migration file to make this?
Rails 2 didn't have an option to create associations via the migration generator, so you have to take a more manual approach.
You can create the migration thusly: https://www.tutorialspoint.com/ruby-on-rails-2.1/rails-migrations.htm
You'll need to add the column student_id to your courses table with a column type of integer
Then add the following to your Student model:
has_many :courses
This shouldn't be too difficult if you are actually using Rails 2.3
And TBH if you aren't AT LEAST on 2.3, then you should probably just recreate this project entirely...
1.) Use ruby script/generate model Course name:string description:text student_id:bigint to generate your migration, which should look something like this:
class CreateCourses < ActiveRecord::Migration
def self.up
create_table :courses do |t|
t.string :name
t.text :description
t.bigint :student_id
t.timestamps
end
end
def self.down
drop_table :courses
end
end
2.) Find the newly created MODEL in your project directory with name course and add the association to the file:
belongs_to :student
3.) Find the STUDENT model in your project folder and add the has_many association to that:
has_many :students
4.) In your terminal, cd into your project folder and run rake db:migrate
You should be good to go after that! Here's the reference for Rails 2.3 associations: https://guides.rubyonrails.org/v2.3/association_basics.html

Ruby on Rails does not generate foreign key from association

I have two set up two database tables called 'points' and 'activities'. I want to give the table 'points' a foreign key 'activity_id' by setting up the associations as follows:
class Activity < ActiveRecord::Base
belongs_to :user
has_many :points, dependent: :destroy
...
end
and
class Point < ActiveRecord::Base
belongs_to :activity
end
In addition, I have the following migrations file for creating the points table:
class CreatePoints < ActiveRecord::Migration
def change
create_table :points do |t|
t.integer :activity_id
t.timestamps null: false
t.boolean :activities_completed, array: true, default: []
t.integer :point_value
t.float :time_left
end
end
end
However, when I run
rake db:reset
rake db:migrate
rake db:seed
and then check the the table points by
rails c
Point.column_names
then the foreign key is missing:
irb(main):001:0> Point.column_names
=> ["id", "created_at", "updated_at", "activities_completed", "point_value", "time_left"]
What am I doing wrong? What can I do to make the foreign key activity_id a column of the points table?
I am new to Ruby and Rails. My Rails version is 4.24. Any help is appreciated.
Your create table migration should have a "t.belongs_to :activity, index: true" instead of creating the field activity_id with type integer.
You should have done something like this to add activity_id to your points table.
t.references :activity, index: true, foreign_key: true
#this would have created activity_id column in points
Since now, you have already created your migrations and ran rake db:migrate, learn to remove a column from a table. You need to write migrations to remove activity_id from your points table and add it again.
rails generate migration RemoveActivityIdFromPoints activity_id:integer
rails g migration AddActivityRefToPoints activity:references
These two should create proper migrations for you. Check your migrations folder for confirmation that everything went well, and run rake db:migrate and test again.
Follow this link to learn more about it. http://guides.rubyonrails.org/active_record_migrations.html
I discovered that there was a more fundamental problem. The migration script was not being executed during rake db:migrate. Therefore the changes I had made to the migration were ineffective. I therefore had to use
rake db:migrate:redo VERSION=20160605234351
When I ran this command, then the foreign key appeared.

Rails Migration Add_Index issue

I'm trying to add indexing to my users table for the email column. Typing rails g migration add_index_to_users_email generates the migration but the function is empty. The snake casing should be correct, so I'm at a loss as to why the migration is being created but the change function inside is empty.
I've also tried AddIndexToUsersName and the same issue arises.
Any direction on what the issue could be would be greatly appreciated. Only thing I can think of is that I'm using Postgres and not MySQL or SQLite, but that wouldn't matter would it?
As far as I know, migration generators only support addition and removal of columns, with a specified modifier. For example, if you wished to add a new string column phone to the users table, you could use the command
rails generate migration AddPhoneToUsers phone:string
Check the Rails Guides for column modifiers. You can try
rails generate migration AddIndexToUsers email:index
to add an index to the existing column. However, I am not sure if generators support column modification. You can write the migration yourself, assuming the email column already exists on the users table:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :email
end
end
Have a look at:
http://guides.rubyonrails.org/active_record_migrations.html
The correct command is
rails g migration AddIndexToUsers email:string:index
This will generate:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :email, :string
add_index :users, :email
end
end
Edit the migration file and delete the add_column line, then run the migration.

add associations to exisiting models

I'm wondering how I can add associations to my models. Suppose, I generate two models
rails generate model User
rails generate model Car
Now I want to add an associations so that the models acquire the form
class User < ActiveRecord::Base
has_many :cars
end
class Car < ActiveRecord::Base
belongs_to :user
end
The question is: how to apply this modification by migrations in order to obtain cars_users table in the database? I'm planning to use that table in my code.
belongs_to association expect an association_id column in its corresponding table. Since cars belongs_to user, the cars table should have a user_id column. This can be accomplished 2 ways.
first, you can generate the column when you create the model
rails g model car user_id:references
or just add the user_id after you create the model like Richard Brown's answer. Be careful that if you use integer instead of references, you'd have to create the index yourself.
rails g migration add_user_id_to_cars user_id:integer
then in the generated migration, add
add_index :cars, :user_id
UPDATE:
As Joseph has mentioned in the comments, the need to add the index manually has already been addressed in the current version of Rails. I think it was introduced in Rails 4. You can read more of it in the official Rails guide for migrations. The gist of it is running the following generator
bin/rails g migration add_user_to_cars user:references
will create a migration with a line similar to
add_reference :cars, :user, index: true
This will add a user_id column to the cars table and it will also mark that column to be indexed.
Following #jvnill's explanation in rails 4 (and maybe in rails 3.2 too) you can do it like this too (avoiding the id parts and remembering the exact convetions):
rails g migration AddUserToCar user:references
Which will create the following migration, taking care of both adding the column and index with all correct conventions:
class AddUserToCar < ActiveRecord::Migration
def change
add_reference :cars, :user, index: true
end
end
At the end as always run the migration:
rake db:migrate
View your schema.rb to view the new index and user_id column.
Generate a migration to create the association:
rails g migration AddUserIdToCars user_id:integer
rake db:migrate
Migration file:
class Createuser < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :name
end
create_table :cars do |t|
t.belongs_to :user, index: true
t.varchar(255) :model
t.varchar(255) :color
end
end
end

Adding an index to a table I already created in SQLite?

Hi I created a table for a wiki application that I was doing. It was pretty simple in the beginning I had a Questions table and an Answers table. I now want to add users to it. So for that I created a users table and the whole signup thing is ready. The wiki part is working and the users part is working but I am having trouble to merge them together.
I first created a Questions as a scaffold as follows:
rails g scaffold Question title:string body:string
Then Answers as follows:
rails g scaffold Answer question_id:integer content:string
I then tried to add the users_id column after creating the Users table:
rails generate migration add_users_id_to_questions user_id:integer
I then tried to index the user_id column by adding the following line in the migration file:
class AddUserIdToQuestions < ActiveRecord::Migration
def change
add_column :questions, :user_id, :integer
end
add_index :questions, :user_id
end
I do rake:db migrate but it doesnt show the change after I run migration. Is there any other way I can index user_id other than by adding a column to the migration file. I even ran rake db:rollback so the addition of user_id column is gone but when I make the change and run rake db:migrate it gives me an error user_id doesnt exist. It would be greatly appreciated if you could help me how to create the index. I running Rails 3, SQLite as my DB.
Thank you.
Rollback and then re-run the migration with add_index inside the change block.
class AddUserIdToQuestions < ActiveRecord::Migration
def change
add_column :questions, :user_id, :integer
add_index :questions, :user_id
end
end

Resources