Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a reference column migration in Rails 5

A user has many uploads. I want to add a column to the uploads table that references the user. What should the migration look like?

Related question for Rails 3: Rails 3 migrations: Adding reference column?

Related question for Rails 4: Add a reference column migration in Rails 4

Related question for Rails 6: How to add reference column migration in Rails 6 with SQLite

like image 512
kkurian Avatar asked Oct 08 '16 22:10

kkurian


People also ask

How do I add a reference column in rails?

When you already have users and uploads tables and wish to add a new relationship between them. Then, run the migration using rake db:migrate . This migration will take care of adding a new column named user_id to uploads table (referencing id column in users table), PLUS it will also add an index on the new column.

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.


1 Answers

As with prior versions of Rails, you may use the following command to create the migration:

rails g migration AddUserToUploads user:references

Unlike prior versions of Rails, the migration looks like:

class AddUserToUploads < ActiveRecord::Migration[5.0]   def change     add_reference :uploads, :user, foreign_key: true   end end 
like image 179
kkurian Avatar answered Oct 08 '22 23:10

kkurian