【发布时间】:2018-03-05 05:19:09
【问题描述】:
我刚刚在 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 运行该任务,它成功了,该列已播种。
在运行迁移之前,是否有我遗漏的步骤或我应该首先运行的任何命令?
【问题讨论】:
-
您是否在添加任务调用之前进行了迁移,然后再次尝试迁移?如果是这样,您需要先回滚迁移,然后再做一次。
-
您可以将
update替换为update!以检查是否发生任何验证错误。 -
是的@MoamenNaanou 我做到了。这只是在此处发布的示例编码。就像你建议的那样,实际的编码更加完整。
标签: ruby-on-rails ruby