Rails Migration with adding and removing reference

Matt Connolly picture Matt Connolly · Apr 13, 2011 · Viewed 51.4k times · Source

After creating a migration file with rails generate migration AddClientToUser I can edit my migration file like so:

class AddClientToUser < ActiveRecord::Migration
  def self.up
    change_table :users do |t|
      t.references :client
    end
  end

  def self.down
    change_table :users do |t|
      t.remove :client_id
    end
  end
end

Is this the correct way to reverse the reference column added in the migration?

Answer

MulleOne picture MulleOne · Apr 28, 2017

Rails 4.2.1

rails g migration RemoveClientFromUsers client:references

Will generate a migration similar:

class RemoveClientFromUser < ActiveRecord::Migration
  def change
    remove_reference :users, :client, index: true, foreign_key: true
  end
end

In addition, one is at liberty to add another or other reference(s) by adding:

add_reference :users, :model_name, index: true, foreign_key: true

within the very change method. And finally running rake db:migrate after saving the changes to the migration, will produce the desired results.