Rails Migration with adding and removing reference Rails Migration with adding and removing reference ruby ruby

Rails Migration with adding and removing reference


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  endend

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.


that is right! and you could also go with:

  def self.down      remove_column :users, :client_id  end


After rails 4 you can do the following

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

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.