Ask A Question

Notifications

You’re not receiving notifications from this thread.

Exporting Records To CSV Discussion

Discussion for Exporting Records To CSV

Is there some magic happening when you call @users.to_csv ?? As I understand @users is an ActiveRecord::Relation, how is the method 'to_csv' sended to the User class ??

Reply

I believe that ActiveRecord::Relation remembers which model class it originated from, so when you call "to_csv" on a Relation it knows to delegate it to the User class. This is how scopes work too. It functions in pretty much the exact same way.

Reply

Good question! Actually to_csv is an instance method of Array. You can see how it is delegated to Array in the method_missing in this file: https://github.com/rails/ra...

Reply

Awesome! I know RailsCast already did this a long time ago, but its great to see it redone with the updates to the syntax.

Reply

Newbie question...I have two models a user model and a coupons model that are associated (coupons belong to user). How do I include the export of a parent model (like user.name field) in the CSV attributes?

Reply

Since that's not an attribute, you can just swap this out:

csv << attributes.map{ |attr| user.send(attr) }

With something like this:

csv << [user.name, user.email, user.coupon.code]

That way you can just reference any attributes or methods you want when exporting and they don't have to be database attributes.

Reply

hi Chris, I tried your advise about csv << [user.name, user.email, user.coupon.code], but now I want customise de headers for the report. how can i do it

Reply

Hey Chris, Thanks for an amazing video. I had trouble with Ryan Bate's course, but yours works perfectly on rails 4.2

I have a question. I have a table with Invoices (scoped by created desc & limit 10) which represents each row on the csv and a table footer which is an active record calculations for the sum of each attributes. I would like to also place them in the csv but haven't found any resource. Could you give me some hint on how I can implement it?

Thanks alot in advance. I really appreciate your contributions. It has made me learn a bunch!

Reply

For that, basically all you need to do is shovel onto the CSV at the end after you loop through the invoices.

You can just say csv << ["custom", "footer"]

Reply

Is it possible to generate csv without templates, i mean i have some field in page like github repository name and date it got created?

Reply

Sure, just transform the params submitted and make the headers and content of the CSV dynamic then.

Reply
Jai Kumar Rajput Jai Kumar Rajput

Really Awesome!!!

Reply

Very well done.
Can you guide me in the direction of making multiple CSV exports on the same model/controller. I can't seem to figure out how to do more than one query-export...

Reply

This one's a little tougher, but the basic idea is this: 1. Export your CSVs to temporary files 2. Zip them up 3. Send the zip file over as the download.

You'll have to do this because there can only be one file downloaded per requests, so hence the need for creating a zip file.

Reply

Any reason why I would prefer CSV over an SQL database? :)

Reply

Very helpful, Chris!

One note on something I ran into... I found on a Rails 4.0 app with Ruby 2.0 that naming the method `to_csv` didn't work. The `to_csv` method from the Ruby CSV seemed to override my method and would just kick out a single row with each object in the set. Renaming the method to `export_csv` solved the problem for me.

Clearly something going on that is unusual in my app configuration, because as I understand it, this method should come "first".

Anyhow, working now!

Reply

What a familiar face. 👋

Good catch, I hadn't run into that but I could see that happening somehow.

Reply

Thank Chris, I found this useful.

Reply

I am a little confused. Why can an array of User objects invoke a class method of User class?

Reply

It's not an Array, it's an ActiveRecord::Relation object. They act like Arrays, but are very different.

Reply

If the data I want not come from mysql records, how to do?

Reply

The generation of CSV should not be done on the Model, it's part of how the data is displayed or represented, so it's part of the View. Dont you think so?

Reply

For the sake of the example, the model is the easiest place to put it. To better organize the code I would probably move this code to its own class but since that's not the concept I want to focus on in this episode, I just placed the code in the model.

Reply

Using the same code set, how would I go about toggling a boolean field, :exported, at the time of export to csv?

Reply

I recently needed to implement something similar to this, but needed to be able to capture the scope passed to the model class and create the CSV based on that scope.

Instead of `all`, use `current_scope` to capture the scope (e.g. `User.where(active: true).limit(10).to_csv`)

https://gist.github.com/mgo...

Reply
Mudedla Panduranga Rao - Mudedla Panduranga Rao -

How attributes will going to help when i need to export relations data as well? If some one any idea, please let me know

Reply
Alejandra Ledesma Alejandra Ledesma

Did you have the same `def self.to_csv` function on the model and the controller?

Reply

transactions.rb

belongs_to :client
def self.to_csv
attributes = %w{id client_id from_date to_date records }

CSV.generate(headers: true) do |csv|
csv << attributes

all.each do |transaction|
csv << transaction.attributes.values_at(*attributes)
end
end
end
Now I need to add client.name to be printed (since client is the parent )?
is there way to do it or any recommended gem to use?

Reply

got it thanx chris

Reply

Thanks for a great episode.
Wanted to give you an example of how to incorporate associated data. The model collection has a partner associated via collection.visit.partner. This csv was setup in the model of collections.
attributes1 is for collection
attributes 2 is for collection.visit.partner
Hope you can use it.

def self.to_csv
attributes1 = %w{quantity size content}
attributes2 = %w{name partner_number address_one postno city}
CSV.generate(headers: true) do |csv|
csv << attributes1 + attributes2
all.each do |collection|
csv << attributes1.map{ |attr| collection.send(attr)} + attributes2.map{ |attr| collection.visit.partner.send(attr)}
end
end
end

Reply

you really helps me a lot! Thanks!

Reply

HI. I am newbie with rails and trying to export records into a csv. I am able to do the simple download, thanks to this wonderful discussion. But my problem is that instead of all.each, I want to iterate over a subset of records. How can I achieve that? Any help would be appreciated. Thanks

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.