自定义ActiveAdmin CSV [英] Customising ActiveAdmin CSV

查看:60
本文介绍了自定义ActiveAdmin CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Activeadmin,并且想在同一CSV文件中导出关联的模型值.我可以得到结果,但格式不正确.我希望所有的问题都是列名,并在行中显示答案.有人可以帮我吗?

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

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

推荐答案

您可以编写自己的csv生成代码.以下是一些脚手架代码,可帮助您入门:

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

祝你好运!

这篇关于自定义ActiveAdmin CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆