简体   繁体   English

将记录导出到CSV

[英]Export A Record To CSV

I have a Posts table in my Rails 3.0.10 app. 我的Rails 3.0.10应用程序中有一个Posts表。 I want to give my users the option to export a particular Post record to CSV format, not all of them. 我想让我的用户可以选择将特定的邮政记录导出为CSV格式,而不是全部导出。 And while my Post table has a lot of fields, I only want to export the title and the body. 尽管我的Post表有很多字段,但我只想导出标题和正文。

After doing some searching apparently the best way to do this is through FasterCSV. 进行一些搜索之后,最好的方法是通过FasterCSV。 And apparently it's already built in Ruby 1.9.2, which I'm using. 显然,它已经在我使用的Ruby 1.9.2中构建。 Thing is pretty much all the tutorials are outdated (from Rails 1 or 2) and I have absolutely no idea how to accomplish this. 几乎所有的教程都已经过时了(从Rails 1或2开始),我绝对不知道如何实现这一点。

I've tried putting in my posts_controller.rb 我尝试放入我的posts_controller.rb

def export_to_csv 
  @post = Post.find(params[:id])
     csv_string = CSV.generate do |csv| 
    csv << [@post.title, @post.body] 
  end 

# send it to the browsah
send_data csv_string, 
          :type => 'text/csv; charset=iso-8859-1; header=present', 
          :disposition => "attachment; filename=post.csv" 
end

Which I THINK may be the right code, but I have no idea how to use it in my view. 认为哪一个是正确的代码,但是我不知道如何在我看来使用它。 Ideally I want to have a link to export the CSV file, but I'm thinking it has to be done through a form_tag? 理想情况下,我想有一个导出CSV文件的链接,但是我认为它必须通过form_tag完成吗?

Would appreciate if someone could point me towards the right direction. 如果有人能指出我正确的方向,将不胜感激。 Thanks. 谢谢。

After several hours of Googling and experimentation I found the answer. 经过数小时的谷歌搜索和实验,我找到了答案。

1.) Install this gem: https://github.com/dasil003/csv_builder 1.)安装此gem: https : //github.com/dasil003/csv_builder

2.) Add respond_to do |format| format.csv 2.)添加respond_to do |format| format.csv respond_to do |format| format.csv to the action you want to turn into a CSV (in my case, the def show part of the posts_controller respond_to do |format| format.csv转换为您要转换为CSV的操作(在我的情况下, def show posts_controller的一部分

3.) Create a action.csv.csvbuilder file (in my case, show.csv.csvbuilder) and add the data you need (in my case, add csv << [@post.title, @post.body] ) 3.)创建一个action.csv.csvbuilder文件(在我的情况下为show.csv.csvbuilder)并添加所需的数据(在我的情况下,添加csv << [@post.title, @post.body]

4.) Add a link to the CSV in the views. 4.)在视图中添加指向CSV的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM