【问题标题】:reload rails environment after migrations迁移后重新加载 Rails 环境
【发布时间】:2017-04-25 06:35:09
【问题描述】:

我有一些定义模型的数据迁移。例如:

db/migrate/19600000000000_some_migration.rb:

class Step < ActiveRecord::Base
end

class SomeMigration < ActiveRecord::Migration
  def change
    # operations requiring the Step class
  end
end

当我在迁移后立即运行种子时

rake db:migrate db:seed

重新定义的Step 类仍在内存中。但我需要最初在app/models/step.rb 中定义的Step 类,因为我的种子依赖于那里的方法,否则它会默默地失败。

有几件事我能想到,但都不是理想的:

  1. require 'app/models/step.rb'播种前
    • 这对我来说真的不起作用,因为它依赖于另一个在迁移中也重新定义的模型,这可能会变成一个兔子洞。
  2. Dir["#{File.dirname(__FILE__)}/app/models/**/*.rb"].each { |f| load(f) }
    • 我也不喜欢这个,因为它重新定义了常量
  3. 始终分别运行 rake db:migraterake db:seed

我尝试寻找在播种后重新加载整个环境的方法,但它们似乎都不起作用:

  • ActionDispatch::Reloader.cleanup!
  • Rack::Reloader.new(MyApp).reload!

对最具可扩展性的方法有什么想法吗?

【问题讨论】:

  • 在一行中分别运行它们:rake db:migrate &amp;&amp; rake db:seed
  • 你也可以试试这个:Step.connection.schema_cache.clear! Step.reset_column_information
  • 我建议在迁移中使用原始 sql 更改数据或使用 rake 任务更改数据。

标签: ruby-on-rails ruby migration reload


【解决方案1】:

试试这个

class SomeMigration < ActiveRecord::Migration
  class Step < ActiveRecord::Base
  end

  def change
    # operations requiring the Step class
  end
end

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2013-10-10
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多