如何在Rails中编写条件迁移? [英] How to write conditional migrations in rails?
问题描述
我正在寻找在Rails中编写迁移的方法,这些迁移可以针对数据库多次执行而不会失败.
I am looking for ways to write migrations in rails that can be executed against the database many times without failing.
例如,假设我进行了迁移:
For instance let say I have this migration:
class AddUrlToProfile < ActiveRecord::Migration
def self.up
add_column :profile, :url, :string
end
def self.down
remove_column :profile, :url
end
end
如果Profile
表中已经存在url
列(例如,如果schema.rb已被意外修改),我的迁移将失败,因为它是重复的!
If the url
column already exists in the Profile
table (if the schema.rb has been modified unexpectedly for instance), my migration will fail saying that it's a duplicate!
那么,仅在必要时如何执行此迁移?
So how to execute this migration only if it has to?
谢谢
推荐答案
您可以执行以下操作:
class AddUrlToProfile < ActiveRecord::Migration
def self.up
Profile.reset_column_information
add_column(:profile, :url, :string) unless Profile.column_names.include?('url')
end
def self.down
Profile.reset_column_information
remove_column(:profile, :url) if Profile.column_names.include?('url')
end
end
这将在开始之前重置列信息-确保Profile模型具有实际表中的最新列信息.然后,它将仅添加不存在的列. down函数也会发生同样的事情,但是它只会删除该列(如果存在).
This will reset the column information before it begins - making sure that the Profile model has the up-to-date column information from the actual table. It will then only add the column if it doesn't exist. The same thing happens for the down function, but it only removes the column if it exists.
如果您有多个用例,则可以将代码分解为一个函数,然后在迁移中重新使用它.
If you have multiple use cases for this you could factor the code out into a function and re-use that in your migrations.
这篇关于如何在Rails中编写条件迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!