2017-09-04 77 views
0

跑我一些轉化數據與軌道遷移: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 

我第一次跑在我的開發環境,一切都順利。 然後我跑在我的生產ENV,但這種失敗:

[email protected]:~/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 
+0

創建它的試過使用bundle exec rake db:migrate? –

+0

感謝您的建議 - 但不幸的是,這並沒有改變任何東西...... – martin

+0

這裏的一個主要問題是,您正在運行'.create'並且從不檢查返回值以查看記錄是否已保存。 – max

回答

1

不是傳遞的instence,因爲它是你可以嘗試更新您的遷移代碼與_id

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

這確實讓我進一步了...現在錯誤來了,我試着更進一步更新實例 – martin

+0

你能發佈那個失敗的日誌嗎? –

+0

'delete_photo'方法中的一件事你可以不用第一行'catalog = Catalog.find self.catalog_id''belgons_to'關聯會讓你自動能夠在模型中調用目錄 –