[ruby-on-rails] Add a reference column migration in Rails 4

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?

Here is what I have. I'm not sure if I should use (1) :user_id, :int or (2) :user, :references. I'm not even sure if (2) works. Just trying to do this the "rails" way.

class AddUserToUploads < ActiveRecord::Migration
  def change
    add_column :uploads, :user_id, :integer
  end
end

Relevant question except for Rails 3. Rails 3 migrations: Adding reference column?

The answer is


Rails 5

You can still use this command to create the migration:

rails g migration AddUserToUploads user:references

The migration looks a bit different to before, but still works:

class AddUserToUploads < ActiveRecord::Migration[5.0]
  def change
    add_reference :uploads, :user, foreign_key: true
  end
end

Note that it's :user, not :user_id


Another syntax of doing the same thing is:

rails g migration AddUserToUpload user:belongs_to

if you like another alternate approach with up and down method try this:

  def up
    change_table :uploads do |t|
      t.references :user, index: true
    end
  end

  def down
    change_table :uploads do |t|
      t.remove_references :user, index: true
    end
  end

Create a migration file

rails generate migration add_references_to_uploads user:references

Default foreign key name

This would create a user_id column in uploads table as a foreign key

class AddReferencesToUploads < ActiveRecord::Migration[5.2]
  def change
    add_reference :uploads, :user, foreign_key: true
  end
end

user model:

class User < ApplicationRecord
  has_many :uploads
end

upload model:

class Upload < ApplicationRecord
  belongs_to :user
end

Customize foreign key name:

add_reference :uploads, :author, references: :user, foreign_key: true

This would create an author_id column in the uploads tables as the foreign key.

user model:

class User < ApplicationRecord
  has_many :uploads, foreign_key: 'author_id'
end

upload model:

class Upload < ApplicationRecord
  belongs_to :user
end

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID


[Using Rails 5]

Generate migration:

rails generate migration add_user_reference_to_uploads user:references

This will create the migration file:

class AddUserReferenceToUploads < ActiveRecord::Migration[5.1]
  def change
    add_reference :uploads, :user, foreign_key: true
  end
end

Now if you observe the schema file, you will see that the uploads table contains a new field. Something like: t.bigint "user_id" or t.integer "user_id".

Migrate database:

rails db:migrate

Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to ruby-on-rails-4

Uninitialized Constant MessagesController Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? NameError: uninitialized constant (rails) How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1) ActionController::UnknownFormat Add a reference column migration in Rails 4 PG::ConnectionBad - could not connect to server: Connection refused Auto-loading lib files in Rails 4 cannot load such file -- bundler/setup (LoadError) Rails 4: how to use $(document).ready() with turbo-links

Examples related to rails-activerecord

Rails 2.3.4 Persisting Model on Validation Failure Add a reference column migration in Rails 4 Rails 4: List of available datatypes ActiveModel::ForbiddenAttributesError when creating new user find vs find_by vs where Combine two ActiveRecord::Relation objects Float vs Decimal in ActiveRecord ActiveRecord find and only return selected columns Rails update_attributes without save? How to change default timezone for Active Record in Rails?

Examples related to rails-migrations

Add a reference column migration in Rails 4 How to drop columns using Rails migration