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?
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
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
# Your one-time task code goes here
# For example, you can call your custom method or do any necessary work
# Close the connection when done (optional)
You can now run your custom rake task and specify the database connection using the
I hope this will be helpful.
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
# do stuff
then from the command line run
rails runner FixDogData.new.fix_dogs