3

我查看了 Rails Guides 和 Rails API,但我无法理解 reversible 和 revert 的用法。

例如,请参阅此处链接的示例http://guides.rubyonrails.org/migrations.html#using-reversible并包含在下面:\

它说 Complex migrations may require processing that Active Record doesn't know how to reverse. You can use reversible to specify what to do when running a migration what else to do when reverting it. For example,

class ExampleMigration < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.references :category
    end

reversible do |dir|
  dir.up do
    #add a foreign key
    execute <<-SQL
      ALTER TABLE products
        ADD CONSTRAINT fk_products_categories
        FOREIGN KEY (category_id)
        REFERENCES categories(id)
    SQL
  end
  dir.down do
    execute <<-SQL
      ALTER TABLE products
        DROP FOREIGN KEY fk_products_categories
    SQL
  end
end

add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end

我知道 down 部分中的代码将在回滚时运行,但为什么要在 up 块中包含代码?我还看到了另一个例子,它有一个可逆部分,只有一个向上块。这样的代码的目的是什么?

最后,我不明白revert。下面是 Rails 指南中包含的示例,但对我来说没有什么意义。

`The revert method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that ExampleMigration is committed and it is later decided it would be best to serialize the product list instead. One could write:
class SerializeProductListMigration < ActiveRecord::Migration
  def change
    add_column :categories, :product_list


reversible do |dir|
      dir.up do
        # transfer data from Products to Category#product_list
      end
      dir.down do
        # create Products from Category#product_list
      end
    end

    revert do
      # copy-pasted code from ExampleMigration
      create_table :products do |t|
        t.references :category
      end

      reversible do |dir|
        dir.up do
          #add a foreign key
          execute <<-SQL
            ALTER TABLE products
              ADD CONSTRAINT fk_products_categories
              FOREIGN KEY (category_id)
              REFERENCES categories(id)
          SQL
        end
        dir.down do
          execute <<-SQL
            ALTER TABLE products
              DROP FOREIGN KEY fk_products_categories
          SQL
        end
      end

      # The rest of the migration was ok
    end
  end
end`
4

1 回答 1

1

无论如何,我都不是这方面的专家,但我通过阅读指南的理解如下:

第一个示例中的reversible调用表示change迁移的四个组件中的第二个。up(注意:您的缩进在这方面具有误导性,可能应该更新以匹配指南。)它与其他组件相关但不同于其他组件,因此它同时具有 an和downsection是有道理的。我无法解释为什么你只会有reversible一个方向而不是另一个方向,正如你所指出的那样。

revert调用告诉系统通过名称或通过提供描述(前向)迁移的块来恢复先前的迁移。您展示的示例是后一种情况,我认为最好通过仔细阅读指南中的段落来理解,即:

同样的迁移也可以在不使用 revert 的情况下编写,但这将涉及更多步骤:颠倒 create_table 和 reversible 的顺序,将 create_table 替换为 drop_table,最后将 up 替换为 down,反之亦然。这一切都由revert处理。

于 2013-11-04T04:20:08.380 回答