活动记录中不可逆迁移的好处?
benefit of irreversible migration in Active record?
我一直在阅读 rails 中的活动记录迁移。大多数时候我们很可能会进行可逆迁移,但我不明白进行不可逆迁移有什么意义?任何人都可以举一些例子吗?使它们不可逆有什么好处?
这是我从rails指南中读到的:
class ChangeProductsPrice < ActiveRecord::Migration
def change
reversible do |dir|
change_table :products do |t|
dir.up { t.change :price, :string }
dir.down { t.change :price, :integer }
end
end
end
end
假设您的 table addresses
中有一个名为 zipcode
的列,其类型当前为 integer
,并且您想将其更改为 string
.
现在,很可能将数据类型从 integer
更改为 string
,但是将 string
更改回整数并不总是可行的,因此我们可以'恢复此迁移。
def self.up
change_column :address, :zipcode, :string
end
现在,如果您这样做 rake db:migrate
,它会正常工作,但是当您要还原它时,您将返回以下错误:
-- Rake aborted!
-- ActiveRecord::IrreversibleMigration
And what's the benefit of making them irreversible?
实际上,我们并不倾向于使它们不可逆;它恰好是不可逆转的。就个人而言,我会选择 always reversible,因为它们非常灵活。
我一直在阅读 rails 中的活动记录迁移。大多数时候我们很可能会进行可逆迁移,但我不明白进行不可逆迁移有什么意义?任何人都可以举一些例子吗?使它们不可逆有什么好处?
这是我从rails指南中读到的:
class ChangeProductsPrice < ActiveRecord::Migration
def change
reversible do |dir|
change_table :products do |t|
dir.up { t.change :price, :string }
dir.down { t.change :price, :integer }
end
end
end
end
假设您的 table addresses
中有一个名为 zipcode
的列,其类型当前为 integer
,并且您想将其更改为 string
.
现在,很可能将数据类型从 integer
更改为 string
,但是将 string
更改回整数并不总是可行的,因此我们可以'恢复此迁移。
def self.up
change_column :address, :zipcode, :string
end
现在,如果您这样做 rake db:migrate
,它会正常工作,但是当您要还原它时,您将返回以下错误:
-- Rake aborted! -- ActiveRecord::IrreversibleMigration
And what's the benefit of making them irreversible?
实际上,我们并不倾向于使它们不可逆;它恰好是不可逆转的。就个人而言,我会选择 always reversible,因为它们非常灵活。