Adrian Serafin Adrian Serafin - 2 years ago 137
Ruby Question

Why does a Rake task in a loop execute only once?

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
:adapter => "postgresql",
:host => user.database_host,
:port => user.database_port,
:username => user.subdomain,
:password => "#{user.database_password}",
:database => user.database_name

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...

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.

Answer Source

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).

Try calling execute on subsequent calls:


The first time through the loop you'll need invoke as it invokes the prerequisites first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download