in rails, how to return records as a csv file

后端 未结 10 1235
醉话见心
醉话见心 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:36

    The following approached worked well for my case and causes the browser to open the appropriate application for the CSV type after downloading.

    def index
      respond_to do |format|
        format.csv { return index_csv }
      end
    end
    
    def index_csv
      send_data(
        method_that_returns_csv_data(...),
        :type => 'text/csv',
        :filename => 'export.csv',
        :disposition => 'attachment'
      )
    end
    

提交回复
热议问题