Rails - CSV(export to CSV) loop

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

i want to do (export to CSV) in the form of fetching first 50 students and next 50 students and so on, in seperate files. i have tried with the below given code, and i dont know how to generate loop, please provide some code to do the process.

 @count =0  if @count == 0  students = Student.find(:all,:order => 'name', :limit => 50)  @count = @count+1  else  students = Student.find(:all,:order => 'name', :limit => 50, :offset => 50)  @count = @count+1 

on clicking export to csv, it should fetch 1st 50 students, next 50 students and so on in different files.

please, tell how to add loop to above code so that it fetches every 50 students, in seperate files

回答1:

in response to theIV and building on his answer you could do

Student.all(:order => 'name').in_groups_of(50, false).each_with_index do |group,index|   export_to_csv("file_number#{index}.csv", group) end 


回答2:

If you are generation csv via a web request to my knowledge you can only send one file per request. So what you need to do is set up your controller to allow pagination. The easiest way to do this is is by using the will_paginate gem (you could alternately send multi files in a zip file)

Install the will_paginate plugin http://github.com/mislav/will_paginate/tree/master

This will allow you to do this in your controller

@students = Student.paginate :page => params[:page], :order => 'name', :per_page => 50 

so http://localhost:3000/controller/action would get the first page with your first 50 records and http://localhost:3000/controller/action?page=2 would get the next 50 etc.

Also you should be probably looking into using respond_to blocks in your controller so it knows http://localhost:3000/controller/action is a html file and http://localhost:3000/controller/action.csv is a csv file

Also see this for a heads up on csv generation in rails, how to return records as a csv file

hope this helps



回答3:

You could try

count = 0 Student.all(:order => 'name').in_groups_of(50, false) do |group_of_students|   export_to_csv("file_number#{count}.csv", group_of_students)   count = count + 1 end 

in_groups_of comes from ActiveSupport, and the false means that it won't pad your 'groups' with anything like nil―if the last group only has 43 students, the array containing that group will only have 43 items, as opposed to sticking a bunch of nils in there and making it 50.

I feel like there should be a nicer way of doing the count, though...



回答4:

You can't return multiple files with one request, HTTP only ever sends one file at once. What you'd want to consider is having the files exported to some safe location, and then downloading from there (via FTP or whatever)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!