Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active admin CSV export custom query scoped

Am using active admin Export CSV option. Its returning all the values related to the particular table.

I want the reports only for a particular month.

Can anyone help?

like image 334
SaravanaKumAr Avatar asked Jan 06 '14 09:01

SaravanaKumAr


2 Answers

you can write own csv exporter

collection_action :download_report, :method => :get do
    users = User.where('created_at >= ?', Date.today - 1.month)
      csv = CSV.generate( encoding: 'Windows-1251' ) do |csv|
      # add headers
      csv < [ #Some header ]
      # add data
      users.each do |user|
        csv << [ user.created_at ]
      end      
    end
    # send file to user
    send_data csv.encode('Windows-1251'), type: 'text/csv; charset=windows-1251; header=present', disposition: "attachment; filename=report.csv"
  end

  action_item only: :index do
    link_to('csv report'), params.merge(:action => :download_report))
  end 

  index :download_links => false do
    # off standard download link
  end

this is just example for you. Your code can be another

like image 65
Philidor Avatar answered Nov 08 '22 07:11

Philidor


for generation csv file use this code where you want

# generate csv file of photo
  def self.generate_csv
    header = []
    csv_fname = "#{CSV_FILE_PATH}/images.csv"
    options = {headers: :first_row}
    photo_columns = column_names - ["id", "updated_at"]
    photo_columns.map{|col| col == "created_at" ? header << "ScrapeDate" : header << col.classify}
    CSV.open(csv_fname, "w", options ) do |csv|
      csv << header if File.exist?(csv_fname) && File.size(csv_fname) == 0
      find_each(batch_size: 5000) do |photo|
        csv << photo.attributes.values_at(*photo_columns)
      end
    end
  end

in above code which column you don't want subtract that cols from actual cols, for example column_names - ["id", "updated_at"] here column_names return actual cols array and which cols we don't need we subtract them.

like image 1
HarsHarI Avatar answered Nov 08 '22 07:11

HarsHarI