2007/11/17

ActiveScaffold: Export records to CSV

CSVファイルにデータをexportするための修正点。

ActiveScaffold を使って Ruby on Rails を機能アップする

より引用。
controllerの変更点。

class UsersController < ApplicationController
active_scaffold :user do |conf|
conf.action_links.add 'export_csv', :label => 'Export to Excel', :page => true
end

def export_csv
# find_page is how the List module gets its data. see Actions::List#do_list.
records = find_page().items
return if records.size == 0

# Note this code is very generic. We could move this method and the
# action_link configuration into the ApplicationController and reuse it
# for all our models.
data = ""
cls = records[0].class
data << cls.csv_header << "\r\n"
records.each do |inst|
data << inst.to_csv << "\r\n"
end
send_data data, :type => 'text/csv', :filename => cls.name.pluralize + '.csv'
end
end
モデルの変更点。
class User < ActiveRecord::Base
# The header line lists the attribute names. ID is quoted to work
# around an issue with Excel and CSV files that start with "ID".
def self.csv_header
   "ID,Last Name,First Name, Email, Birthdate"
end
# Emit our attribute values as a line of CSVs
def to_csv
id.to_s << "," << last_name << "," << first_name << "," << email
<< "," << birthdate.to_s
end
end

0 件のコメント: