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

心已入冬 提交于 2019-12-12 05:12:22

问题


I am using the axlsx gem to generate excel spreadsheets. I am trying to send the generated spreadsheet to the model for zipping. This method zips the excel file with some other files.

The method in my model looks like this:

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

The part I am having problems with is :

  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

How do I get the generated file to the model?


回答1:


I ended up having to render the view from inside the model using: ActionView::Base.new(ActionController::Base.view_paths, {key: value}), thanks to the help I received here.

Below is what ended up working.

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

NOTE: "Model" is the name of the class that this method is in.



来源:https://stackoverflow.com/questions/37194729/rails-send-a-file-generated-by-an-axlsx-view-to-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!