How to download a CSV file in Ruby on Rails?

前端 未结 3 1695
鱼传尺愫
鱼传尺愫 2021-02-02 12:34

In my InvoicesController I have this:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    form         


        
3条回答
  •  清歌不尽
    2021-02-02 13:17

    Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

    # app/controllers/invoices_controller.rb
    format.csv do
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
        render :template => "path/to/index.csv.erb"
    end
    

提交回复
热议问题