Rails initializers are running while migrating database

女生的网名这么多〃 提交于 2019-12-05 18:13:27

问题


It is very surprising that Rails's initializers run while running any rake task, including db:migrate and db:seed.

An initializer in my app starts a background thread (a kind of worker process), and it should be executed only when the application is running in debug and production mode.

How to prevent a specific initializer from running when doing rake db:migrate or how to detect in initializer that a rake task is running?


回答1:


Here is a solution how to prevent an initializer from running in Rake task:

unless ( File.basename($0) == 'rake')
   # Initializer code
end



回答2:


If your initializer depends on the creaton of a specific table, one alternative is to check using ActiveRecord::Base.connection.table_exists? :mytable.




回答3:


Migrates need to load your environment, initializers are an integral part of an environment. If you need an initializer not to run during migrates then it's probably in the wrong place.

If you can't move it elsewhere then perhaps this answer (create a 'fast migrate' rake task) will help.




回答4:


To get around that problem I did this:

if ActiveRecord::Base.connection.table_exists? :settings # check if table exists
  if Setting.first.present? # check if first record has been seeded
    NUMBERS = Setting.first.my_numbers.split(",")
  else
    NUMBERS = '987654321'
  end
else
  NUMBERS = '123456789'
end


来源:https://stackoverflow.com/questions/24136295/rails-initializers-are-running-while-migrating-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!