'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 1:[1]

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

Solution 2:[2]

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 }

Solution 3:[3]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 BenFenner
Solution 3 Muhammad Ushay