2016-05-12 73 views
0

我使用axlsx寶石生成Excel電子表格。我試圖將生成的電子表格發送到模型進行壓縮。此方法將excel文件與其他一些文件進行壓縮。的Rails:發送由axlsx視圖生成的文件到模型

在我的模型的方法是這樣的:

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 

我如何生成的文件將模型?

+0

agustaf,你應該在這裏發表您的最終解決方案,並標記您自己的答案是正確的。 – noel

回答

0

我最後不得不使用模型內部渲染視圖: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 

注:「範式」是類,這種方法是在名稱