什么是相应的回滚?

时间:2011-05-05 10:48:30

标签: ruby-on-rails ruby activerecord rails-migrations

我有以下ActiveRecord迁移:

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

我其实喜欢references风格。很遗憾,我无法在references部分找到相当于self.down的回滚。如果我写remove_column :projects, :subjects_id我也可以写t.integer :subjects_id,这会让它更安全。

1 个答案:

答案 0 :(得分:6)

它被称为remove_references

t.remove_references :subjects

小心! Rails按惯例使用单数,应该是:

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