导出ActiveAdmin CSV中的动态列数

pjm*_*rse 5 csv ruby-on-rails activeadmin

这是使用ActiveAdmin 0.4.3.我们的应用程序运行Surveys,它可能有任意数量的SurveyQuestions.当用户填写调查时,会创建一个UserSurveyComment实例,has_manySurveyComments,每个调查的SurveyQuestions一个.

结果是,对于任何给定的调查,所有UserSurveyComment实例将具有相同数量的SurveyComments,但在调查之间,此数字可能会有所不同.

ActiveAdmin CSV导出是否可以通过这种方式处理UserSurveyComments,以便为用户,调查以及每个SurveyComment提供相应的列?导出的范围是Survey,因此每行具有相同的列,但特定的导出可能具有不同的编号.

我想做的就像是

survey.survey_questions.each do |sq|
  column "Question" { |q| q.survey_comments.where(survey_question_id: sq.id).first.submitted_text }
end
Run Code Online (Sandbox Code Playgroud)

...但是在ActiveAdmin.CSVBuilder实例中,似乎没有办法到达调查.

也许我更容易在自己的控制器中执行此操作?

aja*_*est 3

我理解你的模型类似于

class Survey < ActiveRecord::Base
  has_many :user_survey_comments
  has_many :survey_questions
end

class SurveyQuestion < ActiveRecord::Base

  attr_accessor :name

  belongs_to :survey
  has_many :survey_comments
end

class UserSurveyComments < ActiveRecord::Base
  belongs_to :survey
  has_many :survey_comments
end

class SurveyComments  < ActiveRecord::Base

  attr_accessor :content

  belongs_to :user_survey_comments
  belongs_to :survey_question
end
Run Code Online (Sandbox Code Playgroud)

在块内部csv@collection包含过滤输出的对象列表。在配置中您可以UserSurveyComment通过类似的方式进行注册,如下所示:

ActiveAdmin.register UserSurveyComment do
  csv do

    column(:survey)

    visited_surveys = Set[]

    @collection.each do |user_survey_comment|

      next if visited_surveys.include?(user_survey_comment.survey)
      visited_surveys.add(user_survey_comment.survey)

      user_survey_comment.survey.survey_questions do |question|
        column(question.name) do |user_survey_comment|
          user_survey_comment
            .survey_comments
            .find_by(survey_question_id=question.id)
            .try(:response){''}
        end
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)