2016-05-31 72 views
0

我正在使用CSV类将结果导出到csv。我现在正在工作,但它只将我的搜索查询导出到CSV,而不是结果(显示在我的'show;页面上)。Ruby-Rails将搜索结果表导出为CSV

search.rb

class Search < ActiveRecord::Base 

def to_xls(options = {}) 
    { 
     "Id" => id.to_s, 
     "firstname" => firstname, 
     "surname" => surname, 
     "officenumber" => officenumber, 
     "department" => department, 
     "division" => division, 
     "address" => address, 
     "notes" => notes 
    } 
end 
end 

searches_controller.rb

def show 
    @search = Search.find(params[:id]) 

    respond_to do |format| 
     format.html 
     format.xls { send_data @searches.to_xls, content_type: 'application/vnd.ms-excel', filename: 'search.xls' } 
    end 
end 

mime_types.rb

Mime::Type.register "application/vnd.ms-excel", :xls 
+0

“@搜索”从哪里来?没有显示它的起源。 – tadman

+0

我没有在您的问题的任何地方看到显示CSV导出的代码,因此无法查看是否正在处理正确的数据。 –

回答

2

你应该试试这一个,

def self.to_xls(options = {}) 
    CSV.generate(options) do |csv| 
    csv << column_names 
    all.each do |product| 
     csv << product.attributes.values_at(*column_names) 
    end 
    end 
end 

链接应该像<%= link_to "Excel", your_path(format: "xls") %>

你可以找到完整的流程here来实现它。