我正在使用我的 Ruby on Rails (3) 應用程式設定第二個資料庫,因此我想創建一個 rake 任務來創建第二個開發資料庫。我正在嘗試覆寫rake db:create任務,以便它完成我需要的所有資料庫創建。但是,似乎我找不到合適的方法來執行此任務。我嘗試了幾種方法 - 從 URL 建立到資料庫的連接:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
# database.yml contains an entry for secondary_development, this works, as confirmed from rails console
ActiveRecord::Base.establish_connection "postgresql://localhost/secondary_development"
Rake::Task["db:create"].invoke # this does nothing
end
# invoke original db_create task - this works
db_create.invoke
end
end
另一種方法是:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].invoke
end
# invoke original db_create task - this doesn't work like this
db_create.invoke
end
end
這次只根據secondary_development db:create需要創建作品和資料庫,但development不再使用這種方法創建資料庫。
從我在其他地方找到的一個答案中,我認為重新啟用該任務是必要的,但這并沒有改變這里的任何東西,而且似乎不是問題。
最后,一種行之有效的方法是:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
system("rake db:create RAILS_ENV=secondary_development")
end
db_create.invoke
end
end
這里唯一的問題是,因為 rake 任務是通過 運行system的,Rails 應用程式必須在執行之前加載,所以我實際上是為了運行任務而完全加載應用程式兩次 - 當我添加一個時,這將是 3 次測驗資料庫混入。
所以,實際的問題:
是否可以在Rake::Task["..."]指定環境下以編程方式運行?
為什么ActiveRecord::Base.establish_connection在創建資料庫時不能以這種方式作業?從 Rails 控制臺運行它時我取得了成功。
uj5u.com熱心網友回復:
我設法找到了解決方案。我相信原因是.invoke不會總是呼叫任務,但它會首先確定是否有必要。鑒于rake db:create在同一任務中多次運行,.invoke認為后續呼叫是不必要的,因此不運行它們。對于所需的行為,.execute應改為使用。
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].execute # execute rather than invoke
end
# Reset the Rails env to 'development', otherwise it remains as 'secondary_development', which is not what we want (or move this above the if)
Rails.env = "development"
db_create.execute
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416199.html
標籤:
上一篇:如何為例外指定約束
下一篇:如何從陣列字串中洗掉一些特殊字符
