简体   繁体   中英

Export A Record To CSV

I have a Posts table in my Rails 3.0.10 app. I want to give my users the option to export a particular Post record to CSV format, not all of them. And while my Post table has a lot of fields, I only want to export the title and the body.

After doing some searching apparently the best way to do this is through FasterCSV. And apparently it's already built in Ruby 1.9.2, which I'm using. Thing is pretty much all the tutorials are outdated (from Rails 1 or 2) and I have absolutely no idea how to accomplish this.

I've tried putting in my 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?

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

2.) Add 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

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] )

4.) Add a link to the CSV in the views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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