views:

735

answers:

4

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  A: 

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%5Fpaginate/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%3A3000/controller/action would get the first page with your first 50 records and http://localhost%3A3000/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%3A3000/controller/action is a html file and http://localhost%3A3000/controller/action.csv is a csv file

Also see this for a heads up on csv generation http://stackoverflow.com/questions/94502/in-rails-how-to-return-records-as-a-csv-file

hope this helps

ADAM
+1  A: 

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...

theIV
+4  A: 

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
ADAM
Good call on `each_with_index`! Clearly wasn't thinking there :)
theIV
+1  A: 

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)

Richard Seviora