Add a reference column migration in Rails 5
Asked Answered
S

1

36

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

Schnapps answered 8/10, 2016 at 22:7 Comment(0)
S
76

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
Schnapps answered 8/10, 2016 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.