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
Yet another similar answer, but here's what I usually do.
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.find_each do |model|
csv << model.attributes.values_at(*column_names)
end
end
end
end
Instead of hacking existing module, I'd usually put this code in the ApplicationRecord
class, the base class of all the models (usually).
If any further elaboration is needed, I'd add a named parameter to the to_csv
method, and handle those features as much as possible in this class.
This way, the to_csv
method will be available to both Model and its Relation. E.g.
User.where(role: :customer).to_csv
# => gets the csv string of user whose role is :customer