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

I am trying to run this custom rake task to import data into a Rails 3.1 application:

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 put it in the directory of my applications / tasks.

However, when I try to run rake import_users on the command line, I get this error:

No such file or directory - users.txt

I put user.txt in the same directory as the .rake file (lib / tasks directory), is this the correct location?

+4
source share
1 answer

File names refer to the directory from which you are performing the rake task, and not where the rake file is located. Indicate the absolute path, including the rail installation directory, for example:

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

There is no β€œcorrect” location for afaik import data, but the lib/tasks directory should not be specified. To do this, simply create a dedicated directory under your root rail and point to it in the same way as above.

+8
source

Source: https://habr.com/ru/post/1392369/


All Articles