Question

I am trying to run this custom rake task to import data into my Rails 3.1 app:

desc "Import users." 
    task :import_users => :environment do
        File.open("users.txt", "r").each do |line|
            name, email, age = line.strip.split("\t")
            u = User.new(:name => name, :email => email, :age => age)
            u.save
        end
    end

I saved the file as import_users.rake and placed it in my app's lib/tasks directory.

However when I try to run rake import_users in command line I get this error:

No such file or directory - users.txt

I placed users.txt in the same directory as the .rake file (lib/tasks directory), is that the correct location?

Was it helpful?

Solution

File names are relative to the directory from which you execute the rake task, not where the rake file is located. Specify the absolute path, including your rails installation directory, like this:

File.open(File.join(Rails.root, "lib", "tasks", "users.txt"), "r")

There is no "correct" location for import data afaik, but the lib/tasks directory should not be it. Just create a dedicated directory underneath your rails root for this purpose and point to it in the same manner as above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top