Skip to content

Instantly share code, notes, and snippets.

@mdeiters
Created April 29, 2010 10:18
Show Gist options
  • Save mdeiters/383416 to your computer and use it in GitHub Desktop.
Save mdeiters/383416 to your computer and use it in GitHub Desktop.
#added this method to Game model
#To see more about reading and writing csv files, see http://fastercsv.rubyforge.org/
def self.convert_games_to_csv(games)
require 'fastercsv' #<= This require statement really belongs at the top of the config/environment.rb file
csv = ['home team', 'away team', 'home scroe', 'away score'].to_csv
games.each do |game|
csv << [game.home_team.name, game.away_team.name, game.home_score, game.away_score].to_csv
end
csv
end
#modified this index action in the games controller
def index
@games = Game.all
respond_to do |format|
format.html
format.csv do
#see also send_file (http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M000195&name=send_file)
send_data Game.convert_games_to_csv(@games), :filename => 'games.csv'
end
format.xml do
render :xml => @games.to_xml
end
end
end
<% #Added this link to the games index view %>
<li><%= link_to 'Export Games', games_path(:format => :csv) %></li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment