How to download a CSV file in Ruby on Rails?

前端 未结 3 1693
鱼传尺愫
鱼传尺愫 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 12:58

    I recently discovered

    render_csv
    

    maybe check out this railscast (yay)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-02 13:22

    Try this

    format.csv do
      response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
      response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
    end
    
    0 讨论(0)
提交回复
热议问题