Skip to content

Instantly share code, notes, and snippets.

@januszm
Last active January 13, 2025 15:40
Show Gist options
  • Save januszm/cb751d22f77f915cd3dde332a9057c95 to your computer and use it in GitHub Desktop.
Save januszm/cb751d22f77f915cd3dde332a9057c95 to your computer and use it in GitHub Desktop.
Rails Model to CSV and back
require "csv"
headers = %w[identifier address other]
model = Model
CSV.open("model_export.csv", "wb") do |csv|
csv << headers
model.select(*headers).find_each do |row|
csv << row.attributes.except("id").values
end
end
CSV.foreach("model_export.csv", headers: true) do |row|
record = model.find_by(identifier: identifier)
next unless record
record.update_columns(row.to_h)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment