我刚刚在 rails 中创建了一个迁移,以向现有表添加列。以下是示例代码
class AddShortInfoToDepartment < ActiveRecord::Migration
def self.up
add_column :departments, :short_info, :string
end
def self.down
remove_column :departments, :short_info, :string
end
end
事先,我创建了一个任务文件来为列设定种子。
namespace :db do
namespace :seed do
desc "seed short_info into table departments"
task department_short_info: :environment do
short_infos = [
"Management and Administration",
"Financial",
"Clinical",
"Clinical Support",
"Patient Diet and Ration Management",
"Health Record Management"
]
Department.all.each_with_index do |department, index|
department.update(short_info: short_infos[index])
end
end
end
end
然后我通过添加一行来调用迁移文件中的任务:
class AddShortInfoToDepartment < ActiveRecord::Migration
def self.up
add_column :departments, :short_info, :string
# seeding column short_info using rake task
Rake::Task['db:seed:department_short_info'].invoke
end
def self.down
remove_column :departments, :short_info, :string
end
end
最后,我运行了迁移
rake db:migrate
在添加新列和运行 rake 任务期间都没有错误。
但是,当我在迁移完成后使用控制台进行检查时,表中的"short_info"列没有数据并返回 nil。
为了确保 rake 任务按预期完成其工作,我使用 rake db:seed:department_short_info
运行了该任务,它成功并且列已播种。
在运行迁移之前,我是否错过了某个步骤或任何应首先运行的命令?
没记错的话,当您要进行迁移并在其中执行种子任务时,您必须在要使用的模型上执行#reset_column_information,在您的情况下
Department.reset_column_information
话虽如此,请注意这些事情,因为它会减慢您在生产中的大量推送速度,具体取决于您的数据集大小。