Home > Software design >  Rails Rake Task - Delete records by passing model name and ids as params
Rails Rake Task - Delete records by passing model name and ids as params

Time:05-14

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?

CodePudding user response:

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']

CodePudding user response:

You're sending a string as the ids parameter instead of an array. Your params should instead look like this:

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

CodePudding user response:

I need to split the array of strings and then map it to integers

ids = params[:ids].tr('[]', '').split(' ').map(&:to_i)
  • Related