Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Exporting CSV ignore blanks

I'm trying to create a simple CSV export in Rails. The export works fine except when deleting/archiving table items. I'm guessing this is because the export is encountering blanks.

This is working:

= link_to transactions_path(format: :csv) do

Except when there is a item missing from the transaction.

Tried this

= link_to transactions_path(format: :csv,skip_blanks: true) do

but I still get a ERR_INVALID_RESPONSE when calling the export

TransactionController:

respond_to :html, :json, :csv

def index
   @shops = current_user.shops

   respond_with(@shops) do |format|
     format.csv do
       response.headers['Content-Type']              = 'text/csv'
       response.headers['Content-Disposition']       = "attachment; filename=transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"

       render inline: @shops.to_csv
    end
  end
end

Any suggestions?

like image 816
Jordan Avatar asked Dec 25 '22 08:12

Jordan


2 Answers

Change to_csv to pass skip_blanks.

 @shops.to_csv(skip_blanks: true)
like image 135
Shishir Avatar answered Jan 13 '23 14:01

Shishir


If you want a link to download a CSV file, you should use send_data instead. If you want to display the file in the browser, use render text: @shops.to_csv

http://railscasts.com/episodes/362-exporting-csv-and-excel

respond_to :html, :json, :csv

def index
  @shops = current_user.shops

  respond_with(@shops) do |format|
    format.csv do
      send_data @shops.to_csv, type:'text/csv', filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv"
    end
  end
end

Change your link_to back to what you had before.

= link_to transactions_path(format: :csv)

like image 31
SacWebDeveloper Avatar answered Jan 13 '23 13:01

SacWebDeveloper