gpt4 book ai didi

ruby - Rails 4 ...发送数据后重新加载页面

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:07 25 4
gpt4 key购买 nike

我在 Controller 中有一个方法 export_csv。

def export_csv
if params[:from_date].present? && params[:to_date].present?
@users = User.where("created_at between ? and ?", params[:from_date], params[:to_date])
if !@users.blank?
users_csv = User.to_excel(@users)
send_data(users_csv, :type => 'text/csv', :filename => 'users.csv')
flash.now[:success] = "Successfully downloaded the report!"
else
flash.now[:notice] = "No records over selected duration!"
end
else
flash.now[:notice] = "Select from and to date.."
end
end

文件已下载,但页面未刷新或重新加载。因此,即使在下载文件后,Flash 消息仍会保留在页面上。

我浏览了几个站点,发现 send_data 会自动呈现 View ,因此无法使用其他重定向或呈现。

有没有办法在发送数据后重新加载页面?

最佳答案

send_data 设置整个服务器响应,因此浏览器只接收 CSV 文件,而不是网页。这就是您的即显消息未显示的原因。另一种方法是生成一个临时 CSV 文件(具有随机名称)并返回一个指向它的链接:

def export_csv
if params[:from_date].present? && params[:to_date].present?
@users = User.where("created_at between ? and ?", params[:from_date], params[:to_date])
if !@users.blank?
#Create temporary CSV report file and get the path to it.
csv_file_path = create_csv_file(User.to_excel(@users))

#Change the flash message a bit for requesting the user
#to click on a link to download the file.
flash.now[:success] = "Your report has been successfully generated! Click <a href='#{csv_file_path}'>here</a> to download".html_safe
else
flash.now[:notice] = "No records over selected duration!"
end
else
flash.now[:notice] = "Select from and to date.."
end
end

当然你应该实现函数create_csv_file。为了避免在您的服务器中保留旧文件,您可以实现一种新方法,例如 download_report,它会读取文件,使用 send_data 发送回客户端,最后将其删除。

编辑

上述函数的伪代码:

require 'tempfile'

def create_csv_file(data)
#Create a temporary file. If you omit the second argument of Tempfile.new
#then the OS's temp directory will be used.
tmp = Tempfile.new('report', 'my/temp/dir')
tmp.write(data)
tmp.close

return tmp.path
end


#Method in controller for downloading the file. I omit checks and/or security issues.
def download_report
#Warning: a mechanism should be implemented to prevent the remote
#client from faking the path and download other files.
#A possible solution would be providing not only the file path but also a
#hash with a secret key to validate the path. Function create_csv_file()
#should, then, return a hash in addition of a path.

path = params[:report]
file = File.open(path, "rb")
contents = file.read
file.close

send_data(contents , :type => 'text/csv', :filename => 'users.csv')
file.unlink #Delete file
end

关于ruby - Rails 4 ...发送数据后重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26353740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com