我有一个名为Restream::Custom
的模型,其中有一个属性url
。然后我想将url
属性一分为二:server_url
和 key
,并使两者都成为必需的。我为此编写了这样的迁移:
def up
add_column :restream_customs, :key, :string
Restream::Custom.find_each do |r|
last_slash = r.url.rindex("/")
r.key = r.url[last_slash + 1 .. -1] #everything after last slash
r.url = r.url[0 .. last_slash - 1] #everything before last slash
r.save!
end
change_column :restream_customs, :key, :string, null: false
rename_column :restream_customs, :url, :server_url
end
这在开发方面效果很好。之后,我对restream/custom.rb
进行了大量更改,以便使用server_url
并对其进行验证。因此,此迁移在暂存时失败(并且在生产上将失败(,因为在运行r.save!
时,它会面临validates :server_url, presence: true
并抛出unknown attribute 'server_url' for Restream::Custom
。
如何正确进行此更改?如果可能的话,在一个回合中。(不要多次从存储库中提取(。
更新数据之前将列url
重命名为server_url
def up
add_column :restream_customs, :key, :string
rename_column :restream_customs, :url, :server_url
Restream::Custom.find_each do |r|
last_slash = r.server_url.rindex("/")
r.key = r.server_url[last_slash + 1 .. -1] #everything after last slash
r.server_url = r.server_url[0 .. last_slash - 1] #everything before last slash
r.save!
end
change_column :restream_customs, :key, :string, null: false
end