【问题标题】:Can't populate data to newly added column using rails migration无法使用 Rails 迁移将数据填充到新添加的列
【发布时间】: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


【解决方案1】:

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

Department.reset_column_information

话虽如此,请注意这类事情,因为根据您的数据集大小,它可能会减慢您在生产中的大量推进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2014-12-25
    • 1970-01-01
    • 2017-12-02
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多