Search code examples
ruby-on-railsfilecsvtaskrake

How to read csv file in a rake task


I try to read a file named merchant_data.csv that is stored in lib/tasks/merchant_data.csv where I have this rake task in lib/tasks/import.rake. I get the error No such file or directory @ rb_sysopen - merchant_data.csv. How could I read this file and go through the lines?

task advertiser: :environment do
    CSV.foreach('merchant_data.csv', :headers => true) do |row|
      ...
    end
end

Solution

  • Try to give the full path

    csv_source = Rails.root.join("lib", "tasks", "merchant_data.csv")
    
    CSV.foreach(csv_source, :headers => true) do |row|
      ...
    end