in rails, how to return records as a csv file

后端 未结 10 1233
醉话见心
醉话见心 2020-11-28 05:02

I have a simple database table called \"Entries\":

class CreateEntries < ActiveRecord::Migration
  def self.up
    create_table :entries do |t|
      t.st         


        
10条回答
  •  甜味超标
    2020-11-28 05:34

    Another way to do this without using FasterCSV:

    Require ruby's csv library in an initializer file like config/initializers/dependencies.rb

    require "csv"
    

    As some background the following code is based off of Ryan Bate's Advanced Search Form that creates a search resource. In my case the show method of the search resource will return the results of a previously saved search. It also responds to csv, and uses a view 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 # show.html.erb
          format.csv  # show.csv.erb
        end
      end
    

    The show.csv.erb file looks like the following:

    <%- 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 -%>
    

    On the html version of the report page I have a link to export the report that the user is viewing. The following is the link_to that returns the csv version of the report:

    <%= link_to "Export Report", formatted_advertiser_search_path(@advertiser_search, :csv) %>
    

提交回复
热议问题