Skip to content

Instantly share code, notes, and snippets.

@b-ggs
Forked from bcalloway/rails-export-csv.rb
Created September 25, 2015 03:07
Show Gist options
  • Save b-ggs/a315f5790df28e5e617f to your computer and use it in GitHub Desktop.
Save b-ggs/a315f5790df28e5e617f to your computer and use it in GitHub Desktop.
Use FasterCSV to export an ActiveRecord object in Rails
### /config/environment.rb
config.gem 'fastercsv'
### /config/routes.rb
map.connect '/users/export', :controller => 'users', :action => 'export'
### /app/models/user.rb
# find all students and pass to controller export action for export to csv
def self.find_students
find_by_sql("select students.firstname, students.lastname, students.grade, students.homeroom, students.phone, students.email, students.relationship, users.firstname, users.lastname, accounts.school from students, users, accounts where students.user_id = users.id and accounts.id = users.account_id")
end
### /app/controllers/users_controller.rb
# export students as csv file
def export_students
@students = User.find_students
students_csv = FasterCSV.generate do |csv|
# header row
csv << ["Firstname", "Lastname", "Grade", "Homeroom", "Phone", "Email", "Parent Relationship", "Parent Firstname", "Parent Lastname", "School"]
# data rows
@students.each do |student|
csv << [student.firstname, student.lastname, student.grade, student.homeroom, student.phone, student.email, student.relationship, student.firstname, student.lastname, student.school]
end
end
send_data(students_csv, :type => 'text/csv', :filename => 'schoollife360_students.csv')
end
### view
= link_to 'Export Contacts', '/users/export'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment