Created
July 29, 2009 22:08
-
-
Save bcalloway/158427 to your computer and use it in GitHub Desktop.
Use FasterCSV to export an ActiveRecord object in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### /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' |
@HenleyChiu
export them in which order? the same as db column order? or do you have a requirement for that?
and What to use for the header (the same as the attribute name? to use '-' instead of '_' or use spaces to separate multi word headers?)
and do you need ',' as an attribute separator or ';' or space or even tab?
in short what is your application requirements?
HiH
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I might be missing out on some features of this gem, but to me, this gem misses the whole point of making CSV export easier.. Why do I need to specify all the attributes of the model to put in the CSV? What if I want to export ALL attributes except 1? Just some constructive feedback.