I got an array of ActiveRecord models that I wish to convert to a CSV. I tried researching gems like FasterCSV, but they just seem to work with strings and arrays, not Activ
I had this same problem and combined a couple of these answers so I could call to_csv on a model or relation, then input a file name and create a csv file.
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.to_csv
require 'csv'
p "What is the name of your file? (don't forget .csv at the end)"
file_name = gets.chomp
CSV.open("#{file_name}", "wb") do |csv|
csv << column_names
all.find_each do |model|
csv << model.attributes.values_at(*column_names)
end
end
end
end
Now from console you can call .to_csv
on any model or any db query or activerecord relation.