Search code examples
ruby-on-railsargumentsrake

passing argument to rake task in Ruby on Rails


I am trying to execute multiple rake tasks in a single task. All of the rake tasks are used to update the columns of respective tables. For example if health_post_id >100000 Delete that record

Now i need to pass 100000 as an argument through the command line .But I am not able to figure that out Here is the code

if Rails.env.development? or Rails.env.test?
 namespace :clear_data do


  desc 'clear time slots'
  task :clear_time_slots => :environment do
    TimeSlot.where('health_post_id > ?', p).each do |time_slots|
      time_slots.destroy
    end
  end

  desc "Clean the Practices table"
  task :clear_practice_records => :environment do
      Practice.where('health_post_id > ?', p).each do |practices|
        practices.destroy
      end
  end


  desc "clean database"
  task :clear_database => :environment do |p|
    Rake::Task['clear_data:clear_practice_records'].execute
    Rake::Task['clear_data:clear_time_slots'].execute


    end



 end
 end

Solution

  • I'm not so sure, but I guess you should be able to do:

    if Rails.env.development? or Rails.env.test?
     namespace :clear_data do
      desc 'clear time slots'
      task :clear_time_slots, [:post_id] => :environment do |_, args|
        TimeSlot.where('health_post_id > ?', args[:post_id]).destroy_all
      end
    
      desc "Clean the Practices table"
      task :clear_practice_records, [:post_id] => :environment do |_, args|
        Practice.where('health_post_id > ?', args[:post_id]).destroy_all
      end
    
    
      desc "clean database"
      task :clear_database, [:post_id] => :environment do |_, args|
        max = args[:post_id]
        Rake::Task['clear_data:clear_practice_records'].execute(post_id: max)
        Rake::Task['clear_data:clear_time_slots'].execute(post_id: max)
    
        #OR
    
        #Rake::Task['clear_data:clear_practice_records'].invoke(max)
        #Rake::Task['clear_data:clear_time_slots'].invoke(max)
      end
     end
    end