Last active
January 13, 2025 15:40
-
-
Save januszm/cb751d22f77f915cd3dde332a9057c95 to your computer and use it in GitHub Desktop.
Rails Model to CSV and back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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