2012-12-25 40 views
1

首先,如果這個問題太微不足道了,我真的很抱歉。我是新來的鐵軌,不知道我在哪裏做錯了。如何使用axlsx下載索引頁的搜索結果?

我有一個名爲Costing的模型,在它的索引頁中我有一個搜索表單。我試圖使用'axlsx'寶石只下載搜索結果但我總是得到所有的行。我也使用'will_paginate'寶石。

這是我的代碼。

//costings_controller.rb 

def index 
@costings = Costing.search(params[:search] , params[:page]) 

respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @costings } 
    format.xlsx { 
     send_data @costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet" 
    } 
end 
end 

// index.html.erb 
<%= link_to 'Download Costings', url_for(:format=>"xlsx") %> 

請幫我這裏。 非常感謝。

回答

1

Here是我爲axlsx gem演示製作的代碼。瀏覽它並在控制器中實現您的需求。 Here是這個演示的輸出。

0
//costings_controller.rb 

def download 
@costings = Costing.search(params[:search] , params[:page]) 

respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @costings } 
    format.xlsx { 
     send_data @costings.to_xlsx.to_stream.read, :filename => 'costings.xlsx', :type => "application/vnd.openxmlformates-officedocument.spreadsheetml.sheet" 
    } 
end 
end 

// index.html.erb 
<%= form_for :costing, url: download_costing_index_path do %> 
... 
<% end %> 

//routes 
resources :costing do 
    collection do 
     post :download, :defaults => { :format => 'xlsx' } 
    end 
end 
+0

與其僅僅發佈代碼,嘗試添加一些有關什麼改進和它爲什麼工作的評論。讓你的答案成爲一個教學機會。 – m59