When running generators and migration we can mention name of database in case of multiple databases like this →
bin/rails generate migration CreateDogs name:string --database animals
is there anything similar for running one time rake tasks? where we can mention name of db to connect with like this.
bin/rake one_time_tasks:testing --database animals
Is there any plans in near future by rails to support this?
Hello there,
First, create a custom rake task that takes a database name as an argument. You can do this by creating a new .rake
file in your Rails project’s lib/tasks
directory. Let’s name this task one_time_tasks.rake
:
lib/tasks/one_time_tasks.rake
namespace :one_time_tasks do
desc ‘Run one-time tasks with a specific database connection’
task :testing, [:database] => :environment do |_, args|
database_name = args[:database] || ‘default_database’ # Use ‘default_database’ if no database name is provided
# Establish a connection to the specified database
ActiveRecord::Base.establish_connection(database_name.to_sym)
# Your one-time task code goes here
# For example, you can call your custom method or do any necessary work
# MyOneTimeTask.run
# Close the connection when done (optional)
ActiveRecord::Base.connection.close
end
end
You can now run your custom rake task and specify the database connection using the --database
option:
bin/rake one_time_tasks:testing[–database=animals]
I hope this will be helpful.
1 Like
You could follow the examples in the Rails database tasks to create a task that works the same a rails db:migrate:animals
, but if your task is just a one-time task, it’s probably easier to just create a class and execute it with rails runner
.
class FixDogData
def fix_dogs(dogs_to_fix=Dogs.all)
# do stuff
end
end
then from the command line run
rails runner FixDogData.new.fix_dogs