Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct location for data import file in Rails 3.1 (custom rake task)

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?

like image 247
Andrew Lauer Barinov Avatar asked Feb 21 '23 18:02

Andrew Lauer Barinov


1 Answers

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.

like image 150
Thilo Avatar answered Apr 07 '23 22:04

Thilo