Harakiri
Harakiri

Reputation: 730

Rails: CSV Export

I'm using the built in csv function require 'csv'. But when I try to export the data it only exports records from the current page (with 10 entries) and not all. What should I change?

My sales.controller.rb:

def index
 @sales = Sale.accessible_by(current_ability).order("created_at desc").paginate(:page => params[:page], :per_page => 10)
  respond_to do |format|
    format.html
    format.csv { send_data @sales.to_csv, filename: "sales-#{Date.today}.csv"}
  end
end

My sale.rb Model:

def self.to_csv
 attributes = %w{created_at id brand token customer_id orderid user_id product channel1 channel2}
 CSV.generate(headers: true) do |csv|
   csv << attributes

   all.each do |sale|
     csv << sale.attributes.values_at(*attributes)
   end
 end
end

Upvotes: 0

Views: 296

Answers (1)

Nitin Srivastava
Nitin Srivastava

Reputation: 1424

If you want to get all records instead of pagination then

def index
   @all_sales = Sale.accessible_by(current_ability).order("created_at desc")
   @sales = @all_sales.paginate(:page => params[:page], :per_page => 10)
   respond_to do |format|
     format.html
     format.csv { send_data @all_sales.to_csv, filename: "sales-#{Date.today}.csv"}
   end
end

Enjoy ...!

Upvotes: 3

Related Questions