Reputation: 3149
I have strange problem in this code snippet:
def export_csv
user = User.find_by_u_token(params[:u])
return render json: {status: 'error', descr: 'INVALID_U_TOKEN'} if !user
return render json: {status: 'error', descr: 'INVALID_DELIMITER'} if !user.csv_del
return render json: {status: 'error', descr: 'PARAMS_NOT_DEFINED'} if !params[:invoices]
return render json: {status: 'error', descr: 'INVALID_USER_TYPE'} if !user.contractor? && !user.customer?
invoices = invoices_for_user(user)
pinvoices = params[:invoices].split(' ')
return render json: {status: 'error', descr: 'INVALID_INVOICES'} if !check_invoices(invoices, pinvoices)
export_invoices(pinvoices, user.csv_del)
send_file("file.csv")
return render json: {status: 'ok'}
end
My export_invoices
method:
def export_invoices(pinvoices, delimiter)
CSV.open("file.csv", "wb", {:col_sep => delimiter}) do |csv|
Invoice.find(pinvoices).each do |i|
csv << i.attributes.values
end
end
end
And I have Render and/or redirect were called multiple times in this action.
error.
I've tried to comment the line send_file("file.csv")
and everything works.
Where is the problem?
Upvotes: 2
Views: 1015
Reputation: 1183
Try removing the
return render json: {status: 'ok'}
Reason it will work : cause send_file itself will render, so it doesn't make any sense to do that again.
Upvotes: 0
Reputation: 14051
Basically, the error message you're getting is telling you you can only call render
once.
send_file
is actually doing a render. You get the error when you reach the last line in your code that does another render.
The question is, what do you expect the code to render in the end? is it the CSV file or the json response? you can't have both. So obviously, you want to remove the line in which you return the json response.
Upvotes: 1
Reputation: 911
in above code remove the line return render json: {status: 'ok'}
and create a template export_csv.js.erb here you write your success code
Upvotes: 1