2012-12-25 41 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