Rails:将axlsx视图生成的文件发送到模型

我使用axlsx gem生成excel电子表格。 我正在尝试将生成的电子表格发送到模型以进行压缩。 此方法使用其他一些文件来压缩excel文件。

我的模型中的方法如下所示:

def zipper tempfile = Tempfile.new children = self.children_with_forms Zip::OutputStream.open(tempfile) do |stream| children.each do |child| directory = "#{child.wide_reference[0,3]}/" if child.model_name == "Position" stream.put_next_entry("#{child.volume} #{child.title} TOC.xlsx") stream.print IO.read(Rails.application.routes.url_helpers.toc_path(format: :xlsx, position_id: child.id)) end stream.put_next_entry("#{directory}#{child.wide_reference}-#{child.short_name}-#{child.title.truncate(15, omission:'')}.docx") stream.print IO.read(child.download_form.path) end end tempfile end 

我遇到问题的部分是:

  if child.model_name == "Position" stream.put_next_entry("#{child.volume} #{child.title} TOC.xlsx") stream.print IO.read(Rails.application.routes.url_helpers.toc_path(format: :xlsx, position_id: child.id)) end 

如何将生成的文件添加到模型中?

我最终不得不使用以下方法从模型内部渲染视图: ActionView::Base.new(ActionController::Base.view_paths, {key: value}) ,感谢我在这里收到的帮助。

以下是最终的工作。

 def download tempfile = Tempfile.new children = self.children_with_forms Zip::OutputStream.open(tempfile) do |stream| children.each do |child| directory = "#{child.wide_reference[0,3]}/" if child.model_name == "Position" av = ActionView::Base.new(ActionController::Base.view_paths, {position: child, model: child.model}) stream.put_next_entry("#{directory}#{child.volume} #{child.title} TOC.xlsx") @position = child @model = child.model stream.print av.render template: 'pages/toc.xlsx.axlsx' end stream.put_next_entry("#{directory}#{child.wide_reference} #{child.title.truncate(15, omission:'')} (#{child.short_name}).docx") stream.print IO.read(child.download_form.path) end stream.put_next_entry("Excel File.xlsx") av = ActionView::Base.new(ActionController::Base.view_paths, {model: self}) stream.print av.render template: 'pages/excel_file.xlsx.axlsx' end tempfile end 

注意: “Model”是此方法所在类的名称。