Rails Migration with adding and removing reference

RubyRuby on-Rails-3Rails Migrations

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

that is right! and you could also go with:

  def self.down
      remove_column :users, :client_id
  end

Solution 3 - Ruby

After rails 4 you can do the following

class AddClientToUser < ActiveRecord::Migration
  def change
    add_reference :users, :client, index: true
  end
end

It will handle the up and the down for you, as well as creating a foreign key index. You can also use remove_reference to do the opposite.

Solution 4 - Ruby

With Rails 4 you can just type:

> $ rails generate migration AddClientRefToUser client:references

in the console and this will make the same that Ryan said.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt ConnollyView Question on Stackoverflow
Solution 1 - RubyZeengView Answer on Stackoverflow
Solution 2 - RubyDanielView Answer on Stackoverflow
Solution 3 - RubyRyanView Answer on Stackoverflow
Solution 4 - Rubyxhenryx14View Answer on Stackoverflow