为什么循环中的 Rake 任务只执行一次? [英] Why does a Rake task in a loop execute only once?
问题描述
我有连接到多个数据库的 rails 应用程序.我编写了如下所示的自定义 rake 任务:
I have rails application that connects to multiple databases. I wrote custom rake task that looks like this:
task :migrate_accounts_schema => [:environment] do |t|
users = User.find :all, :conditions => ["state = 2"], :order => "id asc"
users.each do |user|
if user.state == 2
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:host => user.database_host,
:port => user.database_port,
:username => user.subdomain,
:password => "#{user.database_password}",
:database => user.database_name
)
Rake::Task["db:migrate"].invoke
end
end
end
问题是任务只为 users[0] 用户(集合中的第一个用户)执行 db:migrate 并且没有错误,只是静默停止...
The problem is that task executes db:migrate only for users[0] user (first user in collection) and there is no errors, just stoppes silently...
这是 rake --trace 的输出
Here's output from rake --trace
** Invoke app:migrate_accounts_schema (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute app:migrate_accounts_schema
** Invoke db:migrate (first_time)
** Invoke environment
** Execute db:migrate
** Invoke db:schema:dump (first_time)
** Invoke environment
** Execute db:schema:dump
** Invoke db:migrate
我不知道为什么其他用户没有迁移.
I have no idea why the rest of users don't get migrated.
推荐答案
我忘记了确切的内部结构,但 Rake 的工作方式是 invoke
只会在需要时执行每个任务(换句话说一次).
I forgot the exact internals but the way Rake works is that invoke
will only execute each task if it needs to (in other words once).
尝试在后续调用中调用 execute:
Try calling execute on subsequent calls:
Rake::Task["db:migrate"].execute
第一次通过循环时,您需要 invoke
因为它首先调用先决条件.
The first time through the loop you'll need invoke
as it invokes the prerequisites first.
这篇关于为什么循环中的 Rake 任务只执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!