【问题标题】:Customising ActiveAdmin CSV自定义 ActiveAdmin CSV
【发布时间】:2019-02-22 08:25:25
【问题描述】:

我正在使用 Activeadmin,并希望将关联的模型值导出到同一个 CSV 文件中。我能够得到结果,但它的格式不正确。 我希望所有问题都是列名,而答案则显示在行中。谁能帮帮我?

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

【问题讨论】:

  • 我或许可以提供帮助,但我需要了解更多信息:每个 Papplication 的问题数量是否有所不同?每个 pApplcation 是否有一组稳定的 5 个问题?我假设最后一个问题应该在列标题中。
  • @Sjors Branderhost ,是的,每个应用程序的问题会有所不同。没有稳定的 5 til 集,可能会根据要求而有所不同。

标签: ruby-on-rails csv activeadmin


【解决方案1】:

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

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

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多