Lut
Lut

Reputation: 1533

How to import CSV to Rails app

Rails 4.1.7 Ruby 2.1.4

I am trying to upload a CSV file to my app through a controller method:

routes.rb

get 'csv_upload', to: 'users#csv_upload'

users_controller.rb def csv_upload

 require 'csv'    

  customers = CSV.read('customers.csv')

  customers = CSV.parse(csv_text, :headers => true)
  customers.each do |row|
    Moulding.create!(row.to_hash)
  end

  redirect_to users_url

end

CSV File customer.csv

gender ,age
10,20
11,20
12,20
13,20
14,20
15,20

It is located on the root directory. This is the error I get:

Errno::ENOENT in UsersController#csv_upload
No such file or directory @ rb_sysopen - customers.csv

Extracted source (around line #72):
70
71
72
73
74
75


customers = CSV.read('customers.csv')
customers = CSV.parse(customers, :headers => true)

Rails.root: /Users/andreucasadella/rails_projects/hackcdmx

Upvotes: 1

Views: 1753

Answers (2)

Lut
Lut

Reputation: 1533

I finally got it with a task:

lib/tasks/task.rake

namespace :tasks do
    require 'csv'

    desc "cargar usuarios"
    task :load_usuarios => :environment do |t, arg|
        user_files =['lib/datasets/customers.csv']
        user_files.each do |user|
            CSV.foreach(user,:headers => true) do |row|
                id = row.to_hash['id']
                gender = row.to_hash['gender']
                age = row.to_hash['age']
                User.create(id: id,gender: gender,age: age)
            end 
        end 
    end 
end

Created a folder named "datasets" and saved the file "customer.csv" here:

app/lib/datasets/customer.csv

Then executed the task through terminal

rake tasks:load_usuarios

Boom! Ready

Upvotes: 0

Viktor Vsk
Viktor Vsk

Reputation: 327

Exceptions says that file cant be found.
customers = CSV.read('customers.csv') is a relative path. It searches file in current working directory (probably not always in root). You can check working directory with, for example:

raise Dir.getwd.to_s
customers = CSV.read('customers.csv')

and an exception will show you current folder within what file gets searched.

To avoid this, you should better directly specify path with Rails.root, for example:

customers = CSV.read(Rails.root.join('customers.csv'))

Upvotes: 2

Related Questions