无法使用rails迁移将数据填充到新添加的列

问题描述 投票:1回答:1

我刚刚在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运行任务并且它成功并且列被播种。

在我运行迁移之前,是否有一个我错过的步骤或者我应该先运行的任何命令?

ruby-on-rails ruby
1个回答
2
投票

如果我没记错的话,当你想要进行迁移并在其中执行种子任务时,你必须对你要使用的模型执行#reset_column_information,在你的情况下

Department.reset_column_information

话虽如此,请注意这些事情,因为根据您的数据集大小,它可能会减慢您的生产投入。

© www.soinside.com 2019 - 2024. All rights reserved.