【问题标题】:Rails migration will not run in prodRails 迁移不会在 prod 中运行
【发布时间】:2017-09-04 07:17:38
【问题描述】:

我正在使用 Rails 迁移转换一些数据:

class MigrateInstancesToFacets < ActiveRecord::Migration[5.1]
  def change
    say "Found #{Instance.where(rev: nil).count} records to migrate"

    say_with_time "Migrating instances..." do
      user = User.first
      count = 0
      Instance.find_each do |instance|
        CatalogFacet.create(
          photo: instance.photo,
          catalog: instance.catalog,
          user: user
        )
        instance.update(rev: true)
        count += 1
      end
      count
    end
    fail_count = Instance.where(rev: nil).count
    fail "Found #{fail_count} not migrated records" unless fail_count == 0
  end
end

我第一次在我的开发环境中运行它,一切都很顺利。 然后我在我的生产环境中运行它,但是失败了:

pi@pi0:~/pt_api $ RAILS_ENV="production" rake db:migrate
I, [2017-09-04T07:11:51.315838 #29058]  INFO -- : Migrating to MigrateInstancesToFacets (20170831110928)
== 20170831110928 MigrateInstancesToFacets: migrating =========================
-- Found 25671 records to migrate
-- Migrating instances...
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

uninitialized constant Instance::Catalog
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:9:in `block (2 levels) in change'
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:8:in `block in change'
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:5:in `change'
NameError: uninitialized constant Instance::Catalog
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:9:in `block (2 levels) in change'
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:8:in `block in change'
/home/pi/pt_api/db/migrate/20170831110928_migrate_instances_to_facets.rb:5:in `change'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

这是说它无法访问实例上的目录。我打开了一个控制台并在那里运行相同的代码,一切都很好。 迁移时不加载环境吗?

---编辑--- 实例模型:

class Instance < ActiveRecord::Base
  belongs_to :catalog
  belongs_to :photo
  before_destroy :delete_photo

  def delete_photo
    catalog = Catalog.find self.catalog_id
    catalog.delete_photo(self.photo_id)
  end

end

【问题讨论】:

  • 试过使用 bundle exec rake db:migrate?
  • 感谢您的建议 - 但不幸的是,这并没有改变任何东西......
  • 这里的一个主要问题是您正在运行.create 并且从不检查返回值以查看记录是否已保存。
  • 请张贴Instance 型号代码。
  • @GokulM 添加...

标签: ruby-on-rails migration ruby-on-rails-5


【解决方案1】:

您可以尝试更新迁移代码以使用_id 列创建它,而不是按原样传递实例

CatalogFacet.create(
  ...
  catalog_id: instance.catalog_id, 
  ...
)

【讨论】:

  • 这确实让我更进一步......现在错误来了,我尝试进一步更新实例
  • 你能贴出失败的日志吗?
  • delete_photo 方法中的一件事你可以不用第一行 catalog = Catalog.find self.catalog_id belgons_to 关联将使你能够自动调用模型内部的目录
  • 另外,如果你想保持这条线更好地调用::Catalog,这样实例就不会混淆,并尝试在Instance类/模块下搜索Catalog减速跨度>
  • 我进行迁移的原因是为了摆脱实例 - 但你是对的
猜你喜欢
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多