2

我想更改表中的表结构,并且需要用旧字段的值回填一些新字段。因此,为此,我想在迁移中使用存储库。但是,我似乎需要加载 Hanami 模型才能使用存储库,因为 Hanami 在运行迁移时不会加载它。

所以,现在我有这个:

require_relative '../../lib/my_app/repositories/entity_repository'
require_relative '../../lib/my_app/entities/my_entity'

Mutex.new.synchronize do
  Hanami::Model.load!
end

Hanami::Model.migration do
  change do
    def backfill_data!
      repo = EntityRepository.new

      repo.all.map do |entity|
        repo.update entity.id, new_field_as_date: Date.new(entity.old_field)
      end
    end

    backfill_data!
  end
end

但是在运行此迁移时,我得到

bundler: failed to load command: hanami (/Users/user/.rbenv/versions/2.4.1/bin/hanami)
Hanami::Model::Error: key not found: :person
# which is an association with the entity mentioned on the code

所以,我不知道现在该怎么办。最大的问题是,如何在 Hanami 迁移中迁移数据?

4

1 回答 1

3

我不知道这个具体问题,但我强烈建议您在迁移中使用存储库。由于存储库与数据库表的当前模式紧密相关,因此如果您将来运行相同的迁移,它可能无法正常工作。

您应该直接使用数据库设施。这将保证迁移始终有效:

Hanami::Model.migration do
  up do
    run "UPDATE users SET last_login_at=(last_login_at - INTERVAL '1 day')"
  end

  down do
  end
end
于 2017-10-05T14:43:42.067 回答