Prev | Current Page 409 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

In addition, CSV is a popular file type for importing or
exporting from legacy systems or providing information to users for importing into their
spreadsheet or other programs. Because the Ruby standard libraries contain CSV reading and
writing capabilities, output of Active Record objects as CSV data is straightforward.
In the following example code, we export all of our accounts to a CSV file. We utilize the
Account model??™s content_columns method to give us just the content of the class; this excludes
the primary key, all columns ending in _id or _count, and the column used for single-table
inheritance. If, for instance, you do not wish to export only the content columns and you actually
want all of the columns, you can replace the calls to content_columns with columns.
headers = Account.content_columns.collect { |column| column.human_name }
only_columns = Account.content_columns.collect { |column| column.name }
accounts = Account.find(:all)
outfile = File.open('csvoutput.csv', 'wb')
CSV::Writer.generate(outfile, ',') do |csv|
csv << headers
accounts.


Pages:
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421