对应的回滚是什么?

发布于 2024-11-04 22:21:51 字数 632 浏览 1 评论 0原文

我有以下 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 样式。不幸的是,我在 self.down 部分中找不到与 references 等效的回滚。如果我写 remove_column :projects, :subjects_id 我也可以写 t.integer :subjects_id,这样会更安全。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

︶葆Ⅱㄣ 2024-11-11 22:21:51

它称为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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文