Skip to main content

Exporting to CSV and including records from related models

Rails • Asked by RJ McCollam

I have a user model in my application that has instances of 3 other models and what I am trying to do is to export to CSV all of the user information as well as the information for the other models related to that user.

In following the Export to CSV video on GoRails I am able to export all of the user's data through CSV, but am not sure how to also include records from these other models.

Since each user will have different totals of these other models I understand I probably cannot put all the data of a user on one line and would have to break it down like:

User Data
Parent Data for Above User
Medication Data for Above User

I'm not sure how to loop through these other models related to the user and output there data in my to_csv function.

Here is the code I am using to generate the CSV currently:

CSV.generate(headers: true) do |csv|
  csv << attributes
      all.each do |user|
          csv << user.attributes.values_at(*attributes)
    end
end

Is this even possible considering that the headers would be different? Should I just make them separate exports?

Edit - Maybe a better question is if I break these out into separate CSV's I would only have the user_id in order to allow any association between users and the data in other CSV's.

How would I go about pulling in a value from the User model using the user_id in a CSV export for another model? For example in my parents export I wont to include the user's student_id.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.