gpt4 book ai didi

ruby-on-rails - 在 Active Record 迁移中可逆和还原

转载 作者:行者123 更新时间:2023-12-04 06:28:23 25 4
gpt4 key购买 nike

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

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

它说复杂的迁移可能需要 Active Record 不知道如何反转的处理。您可以使用 reversible 来指定运行迁移时要执行的操作以及还原迁移时要执行的其他操作。例如,

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 block 中?我还看到了另一个例子,它有一个只有向上挡 block 的可逆部分。这样的代码的目的是什么?

最后,我不明白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`

最佳答案

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

第一个示例中的reversible 调用表达了change 迁移的四个组成部分中的第二个。 (注意:您的缩进在这方面具有误导性,可能应该更新以匹配指南。)它与其他组件相关但又不同,因此它同时具有 updown 部分。我无法解释为什么只有一个方向而不是另一个方向的可逆,正如您所看到的那样。

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

The same migration could also have been written without using revert but this would have involved a few more steps: reversing the order of create_table and reversible, replacing create_table by drop_table, and finally replacing up by down and vice-versa. This is all taken care of by revert.

关于ruby-on-rails - 在 Active Record 迁移中可逆和还原,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com