What is the appropriate rollback?

I have the following ActiveRecord migration:

class CreateSubjects < ActiveRecord::Migration
  def self.up
    create_table :subjects do |t|
      t.string :title
      t.timestamps
    end

    change_table :projects do |t|
      t.references :subjects
    end
  end

  def self.down
    drop_table :subjects
    remove_column :projects, :subjects_id #defeats the purpose of having references
  end
end

I like the style references. Unfortunately, I could not find the rollback equivalent referencesin the section self.down. If I write remove_column :projects, :subjects_id, I can also write t.integer :subjects_idwhat would make it safer.

+5
source share
1 answer

It is called remove_references .

t.remove_references :subjects

Be careful! Rails uses a singular convention, should be:

def self.up
  create_table :subjects do |t|
    t.string :title
    t.timestamps
  end

  change_table :projects do |t|
    t.references :subject
  end
end

def self.down
  drop_table :subjects
  change_table :projects do |t|
    t.remove_references :subject
  end
end
+6
source

All Articles