0

I have tried the following for importing data from csv file in rails but couldn't understand where I have to use the particular code and how to save particular db column with specific columns of CSV.

require 'csv'    
csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
User.create!(row.to_hash)
end

And where should we keep the csv file to be imported. Can we give path like /Downloads/users.csv in File.read()? And what if the field in csv file is referenced by another table and can we use like the following:

require 'csv'    
csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
Project.new
Project.client = project.where(:client_code, row.client_code)

Can we use something like this?

projects.csv:

project_code    project_name    client_code
   P1               Proj1         C1
   P2               Proj2         C2
   P3               Proj3         C3

clients.csv

client_code    client_name
   C1           Client1
   C2           Client2

project.rb(Model) belongs_to :client

client.rb(Model) has_many :projects

So, in projects.csv, I have client_code by which I have to load client_id into the db.

projects table in db:

project_id  project_code  project_name  client_id

I have referred the following link but couldn't understand completely. Ruby on Rails - Import Data from a CSV file

Community
  • 1
  • 1
Nandy
  • 57
  • 8
  • 1
    Can you post an example of your csv file? – lcguida Jun 16 '16 at 13:22
  • You could always put this in a rake task, schedule a cron job to run this task frequently (or as needed). You can save the CSV file wherever within your project. –  Jun 16 '16 at 18:08
  • @lcguida. I have updated the question which has csv samples. – Nandy Jun 17 '16 at 04:45
  • @Tommyixi, everything you said was done and it works but the entire data gets inserted twice. ie., If the no of rows is 32 it inserts 64(all twice) – Nandy Jun 17 '16 at 07:03

0 Answers0