Ruby Rails 4…发送数据后重新加载页面
我在控制器中有一个导出csv的方法Ruby Rails 4…发送数据后重新加载页面,ruby,ruby-on-rails-4,actioncontroller,Ruby,Ruby On Rails 4,Actioncontroller,我在控制器中有一个导出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.
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会自动渲染视图,因此无法使用其他重定向或渲染
是否有方法在发送数据后重新加载页面?
send\u data
设置整个服务器响应,因此浏览器只接收CSV文件,而不是网页。这就是为什么您的flash消息没有显示。另一种方法是生成一个临时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
谢谢你的回复。没有别的方法吗?因为,使用后台任务删除文件将是一件繁忙的事情。那么,您可以创建一个新方法
下载\u csv
,该方法将使用发送\u数据
(首先读取文件内容),然后删除该文件。您可以帮助编写创建\ucsv文件和下载报告的伪代码吗?好的,我已经为你写了一些代码。如果存在安全问题,请阅读代码注释中的警告。
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