Skip to content

Exporting data to CSV in rails console

I’ve had a similar post to this in the past where I exported an entire table to CSV, but what if you want to export only a subset of that data? Well, that’s what this post is for :)

  1. Start with a query that narrows things down as much as possible
  2. Then loop through those results to apply any additional filtering you need
  3. Finally generate the CSV file with a header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
date = Date.new(2016,12,15)
l = Table.where("created_at > ? AND column != 'variable'", date)
 
ActiveRecord::Base.logger = nil
results = []
l.each do |i|
 u = User.where(:email => i.email)
 if u.present?
   if Table.where(:email => u[0].email).blank?
     results << {:email=>i.email,:member=>'y'}
   end
 else
   results << {:email=>i.email,:member=>'n'}
 end
end;0
 
 
require 'csv'
 
file = "#{Rails.root}/public/data.csv"
 
CSV.open( file, 'w' ) do |writer|
 writer << results.first.map { |a,v| a }
 results.each do |s|
 writer << s.map { |a,v| v }
 end
end
 
 
Published inTime Wasters

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *