Another way to do this without using FasterCSV:
Require ruby ββcsv library in initializer file, e.g. config / initializers / dependencies.rb
require "csv"
Like some background, the following code is based on Ryan Bateβs advanced search form , which creates a search resource. In my case, the show method of a search resource returns the results of a previously saved search. It also responds to csv and uses a presentation template to format the desired output.
def show @advertiser_search = AdvertiserSearch.find(params[:id]) @advertisers = @advertiser_search.search(params[:page]) respond_to do |format| format.html
The show.csv.erb file is as follows:
<%- headers = ["Id", "Name", "Account Number", "Publisher", "Product Name", "Status"] -%> <%= CSV.generate_line headers %> <%- @advertiser_search.advertisers.each do |advertiser| -%> <%- advertiser.subscriptions.each do |subscription| -%> <%- row = [ advertiser.id, advertiser.name, advertiser.external_id, advertiser.publisher.name, publisher_product_name(subscription), subscription.state ] -%> <%= CSV.generate_line row %> <%- end -%> <%- end -%>
In the html version of the report page, I have a link to export the report that the user is viewing. Below is the link_to link, which returns the csv report version:
<%= link_to "Export Report", formatted_advertiser_search_path(@advertiser_search, :csv) %>
rwc9u Oct 21 '08 at 17:16 2008-10-21 17:16
source share