Reputation: 1457
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?
Upvotes: 4
Views: 587
Reputation: 780
Change to_csv to pass skip_blanks.
@shops.to_csv(skip_blanks: true)
Upvotes: 6
Reputation: 10807
Maybe using send_data
:
def index
respond_to do |format|
format.csv { send_data @current_user.shops.to_csv, filename: "transactions-#{Time.now.strftime('%Y%m%d%H%M')}.csv" }
end
end
Also, is the to_csv
an instance method?
Upvotes: 1
Reputation: 2812
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)
Upvotes: 3