Skip to content

Instantly share code, notes, and snippets.

@abhianair
Last active July 29, 2019 09:27
Show Gist options
  • Save abhianair/5b8266eb39f856045ee0ef24396e907a to your computer and use it in GitHub Desktop.
Save abhianair/5b8266eb39f856045ee0ef24396e907a to your computer and use it in GitHub Desktop.
Rails export to csv multiple table in a same file
def backup
models = ["table1s","table2s","table3s"]
all_data = Hash.new
models.map do |model_name|
table_data = []
model_name = model_name.split("")
model_name.pop
model_name = model_name.join("")
model_name.camelize.constantize.all.map do |data|
table_data.push(data)
end
all_data[model_name.camelize] = table_data
end
send_data export_csv(all_data), filename: "Export - #{Date.today}.csv" and return
end
def export_csv(data)
csvfile = CSV.generate(headers: true) do |csv|
data.each do |key, value|
csv << [key]
attributes = key.camelize.constantize.column_names
csv << attributes
value.each do |val|
csv << val.attributes.values_at(*attributes)
end
csv << ['eot']
end
end
return csvfile
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment