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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With