在我的控制器操作PagesController#transfer
中,我想下载一个xml文档,然后重新加载页面。
但是xml文档是用render_to_string
生成的,因此下载文件后尝试添加重定向时会出现错误。
此操作的目标是在下载XML之后获得即显消息。因此,重新加载页面似乎是一个不错的选择。
pages_controller
def transfer
...
multiple_export_to_sepa(objects, @errors)
end
private
def multiple_export_to_sepa(objects, errors)
sepa_filename = "virements_#{params[:type]}.xml"
if objects.present?
stream = render_to_string(template: "admin/pages/transfers_#{params[:type]}.xml", layout: false)
send_data(stream, type: 'text/xml', filename: sepa_filename , status: :created)
flash[:success] = "#{objects.length} objects has been generated."
redirect_to action: :transfer
else
redirect_to action: :transfer
end
end
答案 0 :(得分:0)
您是否尝试过使用flash.now
?
def multiple_export_to_sepa(objects, errors)
sepa_filename = "virements_#{params[:type]}.xml"
if objects.present?
stream = render_to_string(template: "admin/pages/transfers_#{params[:type]}.xml", layout: false)
send_data(stream, type: 'text/xml', filename: sepa_filename , status: :created)
flash.now[:success] = "#{objects.length} objects has been generated."
else
redirect_to action: :transfer
end
end
从文档(http://guides.rubyonrails.org/action_controller_overview.html#flash-now):
5.2.1 flash.now 默认情况下,向闪存添加值将使它们可用于下一个请求,但是有时您可能希望在同一请求中访问这些值。例如,如果create操作无法保存资源,而您直接呈现新模板,则不会导致新的请求,但是您可能仍想使用Flash来显示消息。为此,您可以使用Flash.now,方法与使用常规Flash相同:
class ClientsController < ApplicationController
def create
@client = Client.new(params[:client])
if @client.save
# ...
else
flash.now[:error] = "Could not save client"
render action: "new"
end
end
end