我正在使用rails migration转换一些数据:
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)
它说无法访问实例上的目录。我打开了一个控制台并在那里运行相同的代码,这一切都很好。 是否在迁移时没有加载环境?
--- --- EDIT 实例模型:
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
答案 0 :(得分:1)
您可以尝试更新迁移代码,使用_id
列
CatalogFacet.create(
...
catalog_id: instance.catalog_id,
...
)