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