【问题标题】:Rails: Send a file generated by an axlsx view to a modelRails:将由 axlsx 视图生成的文件发送到模型
【发布时间】:2016-05-12 18:25:22
【问题描述】:

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

如何将生成的文件获取到模型中?

【问题讨论】:

  • agustaf,您应该在此处发布您的最终解决方案并将您自己的答案标记为正确。

标签: ruby-on-rails ruby axlsx


【解决方案1】:

我最终不得不使用ActionView::Base.new(ActionController::Base.view_paths, {key: value}) 从模型内部渲染视图,感谢here 的帮助。

下面是最终的工作。

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

注意:“模型”是该方法所在的类的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2019-05-11
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多