Question

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 actually like the references style. Unfortunately I could not find the rollback equivalent of references in the self.down section. If I write remove_column :projects, :subjects_id I can as well write t.integer :subjects_id, which would make it safer.

Was it helpful?

Solution

It is called remove_references.

t.remove_references :subjects

Be careful! Rails uses singular by 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top