2010-11-29 53 views
21

我需要在導軌應用程序中將數據導出爲CSV格式。我發現這個插件:https://github.com/crafterm/comma。你知道一些更好的解決方案嗎?在導軌中將數據導出爲CSV

+3

看起來相當全面和處理數據關係,我會說**堅持**逗號** – ocodo 2010-11-29 08:44:44

+1

逗號在rails3中不適用於我。我發現https://github.com/econsultancy/csv_builder,它運作良好。 – boblin 2010-11-29 10:48:02

回答

37

如果使用Ruby 1.9.x,則使用CSV而不是FasterCSV並使用默認分隔符。

控制器:

respond_to do |format| 
    ...   
    format.csv { render :layout => false } 
end 

show.csv.erb:

<%= this_is_your_view_helper_method.html_safe %> 

controller_helper.rb:

require 'csv' 

def this_is_your_view_helper_method 
    CSV.generate do |csv| 
    Product.find(:all).each do |product| 
     csv << ... add stuff here ... 
    end 
    end 
end 
2

結帳此堆棧溢出answer用於Ruby的1.9.x的使用CSV (正如Fletch指出的,它包含FasterCSV,但語法略有不同)。