Search code examples
ruby-on-railsrubyactiverecordrake

Figuring out how rake works and how command line arguments can be handled in a rake tasks in rails


How can I pass arguments to a rake task so that it executes the rake task on a different schema? For example I have rake code such as the one below:

namespace :update_persons_table do
  task :import => :environment do

  config   = Rails.configuration.database_configuration
  ActiveRecord::Base.connection.schema_search_path = "my, public, data_master_reports"  

       # do stuff make updates to table....

  end
end

I call this rake task from the command line like this:

RAILS_ENV='production' rake update_persons_table:import

BTW, does the above RAILS_ENV call I am using have to do with the :environment do statement I am using in the second line? Because in my database.yml file i do have a production: database entry. Im trying to figure out how the whole plumbing for this works. This rake task updates a table in a database. But I want to be able to call it on another clone table in a different database. How can I do that with passing parameters in the command line?


Solution

  • How can I pass arguments to a rake task so that it executes the rake task on a different schema?

    I think what you are asking is

    How can I pass arguments to a rake task so that it executes the rake task on a different environment?

    The schema is the same for all environments of your app

    does the above RAILS_ENV call I am using have to do with the :environment do statement I am using in the second line?

    Yes :environment do will take whatever environment(:development, :test, :production) you are specifying. In your example, its RAILS_ENV='production'

    Now to run the rake task in a different environment, like say the development environment

    `RAILS_ENV='development' rake update_persons_table:import'
    

    Now the same code that was executed on the production environment db when you ran `RAILS_ENV='production' rake update_persons_table:import' has been run in the development environment db

    Hope this is clear enough to get you started