Anukrity Anukrity - 3 years ago 146
Ruby Question

Need to export data from multiple models to csv in ruby on rails

I have created a simple export which is able to export all fields of a model to a csv, but now I need to export some attributes from another model which has a has_many relationship with that model

my controller file looks like

respond_to do |format|
format.html
format.csv { send_data @students.as_csv, filename: "students-#{Date.today}.csv" }
end


student.rb

def self.as_csv
attributes = %w{surname given_name admission_year admission_no hobbies }
CSV.generate do |csv|
csv << attributes
all.each do |item|
csv << item.attributes.values_at(*attributes)
end
end


It works fine but because hobby is another table having a has_many relation with student as a student has many hobbies, I want to show hobbies for each student a a comma separated list in the csv. I am stuck as to how to achieve this.

Any help will be appreciated.

Answer Source

I would just do something like this:

CSV_HEADER = %w[surname given_name admission_year admission_no hobbies]
def self.as_csv
  CSV.generate do |csv|
    csv << CSV_HEADER
    all.each do |student|
      csv << [
        student.surname, 
        student.given_name, 
        student.admission_year,
        student.admission_no,
        student.hobbies.pluck(:title).join(', ')
      ]
    end
  end
end

You may need to adjust title with a attributes name that returns the hobby as a string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download