Loading Excel Data Into an ActiveRecord Database

CSV files

Read a .csv file

data = CSV.read(“path/my_csv_file.csv”)data[0][1] #=> data from the first row and the second column
data = CSV.parse(File.read((“path/my_csv_file.csv”), headers: true)data[0][1] #=> data from the first non-header row and the second column

Save the data in your database

Create

data.each do |row|
Model.create(
name: row[0]
age: row[1]
email: row[5]
)
end
data.each do |row|
Model.create(
name: row[“name”]
age: row[“age”]
email: row[“email”]
)
end

Update

data.each do |row|
student = Model.find_by(name: row["name"])
student.update(
email: row[“email”]
)
end

--

--

Current Web Development student at https://flatironschool.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store