ruby-on-railsrake-task

Rails Rake Task - Delete records by passing model name and ids as params


I am intending to write a generic rake task that allows me to destroy a model's records after taking in model name and ids as input params

  #lib/tasks/import.rake

  task :destroy_model_records, [:params] => :environment do |task, args|
    params = args.params.with_indifferent_access
    model = params[:model_name]
    ids = params[:ids]

    model.where(id: ids).destroy_all
  end

Here's what my params look like:

params = { ids:"[532]", model_name: Shop }

I've tried this but this does not return an error message and neither does it perform an operation, what am I missing here?


Solution

  • Try to load the model with Object.const_get(model) Then it will read the class on which the 'where' method should work. To verify the parameters, you can write them out using the puts method.

    #lib/tasks/import.rake
    
    task :destroy_model_records, [:model_name, :ids] => :environment do |t, params|
      puts params[:model_name]
      puts params[:ids]
    
      model = Object.const_get(params[:model_name])
      ids = params[:ids].split(" ")
    
      model.where(id: ids).destroy_all
    end
    
    

    And the task can be done like this:

    rails import:destroy_model_records[Shop,'1 2 3']