Customising ActiveAdmin CSV

杀马特。学长 韩版系。学妹 提交于 2021-01-29 07:34:44

问题


I am using Activeadmin and would like to export the associated model values in the same CSV file. I am able to get the result but its not in a proper format. I want all the question to be the column name and the answer for that to be displayed in the row. can anyone help me?

Papplication.rb

ActiveAdmin.register Papplication do
 csv do
  column "Questions" do |papp|
    @questions.map do |question|
      question.question_text
    end
  end
  column "Answers" do |papp|
    @questions = Question.where(:program_id=>papp.program_id)
    @answers = Answer.where(:question_id => @questions.ids,:startup_id => papp.startup_id)
    @questions.map do |question|
        Answer.where(:question_id => question.id, :startup_id => @startup.id).first.answer_text
    end
  end
end


回答1:


You can write your own csv generation code. Here is some scaffolding code to get you started:

sidebar :download_as_csv, :only => [:index] do
  a(href: download_as_csv_admin_papplications_path(params.slice(:scope, :filter))) do
    'Download as csv'
  end
end

collection_action :download_as_csv, :method => :get do
  # define your own headers
  csv_headers = ["Question 1", "Answer 1", "Question 2", "Answer 2"] # customize yourself
  rawcsv = CSV.generate(:col_sep => ",") do |csv|
    # here you could add headers
    # csv << csv_headers
    # scoped_collection is provided by activeadmin and takes into account the filtering and scoping of the current collection
    scoped_collection.each do |papplication|
      csv_row = []
      # Create a convenience method in the Papplication model that returns a hash of question_text to answer_text
      papplication.questions2answers_hash.each do |question, answer|
        csv_row << question
        csv_row << answer
      end
      csv << csv_row
    end
  end
  send_data(rawcsv, :type => 'text/csv charset=utf-8; header=present', :filename => Time.now.strftime("%Y%m%e-%H%M%S")) and return
end

Good luck!



来源:https://stackoverflow.com/questions/54822857/customising-activeadmin-csv

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