'Export CSV File with custom headers and values Rails

I have an export CSV method which works fine. To this, I would like to add the associated model values in the same CSV file.

def self.to_csv(subjects, headers, study)
  CSV.generate(headers: true) do |csv|
    csv << headers
    subjects.each do |subject|
      generate_data(csv, study, subject)
    end
  end
end
def self.generate_data(csv, study, subject)
  values = []
  values += get_data(study, subject)
  csv << values
end
def get_data(study, subject)
  data = [
    study.title,
    study.id,
    study.category
 ]
 data.flatten
end

I want that to be in this format. where the subject has_many associations with the programs. I want to customize the header with the number of programs associated with the subject by incrementing by 1 "program_#{i+1}" and the corresponding program.name should be the value. Can anyone guide me to achieve this? CSV File



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source