Wednesday, March 22, 2023

Import CSV Rake task

 # lib/tasks/import_csv.rake

namespace :csv do

  desc "Import CSV file"

  task import: :environment do

    require 'csv'


    # Replace 'your_controller' and 'your_action' with the actual controller and action names

    controller = YourController.new

    file_path = Rails.root.join('path', 'to', 'your', 'csv_file.csv')

    file = File.open(file_path)


    # Wrap the file in a Rack::Test::UploadedFile instance

    uploaded_file = Rack::Test::UploadedFile.new(file, 'text/csv')


    # Call the controller action

    controller.your_action(uploaded_file)


    file.close

  end

end