簡體   English   中英

Rails:將由axlsx視圖生成的文件發送到模型

[英]Rails: Send a file generated by an axlsx view to a model

我正在使用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

注意: “模型”是此方法所在的類的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM