1

我想在我的 ruby​​ 3.2.8 应用程序中创建一个包含两个带有逗号 gem 的模型的 CSV 文件。也许这个问题的答案是微不足道的,但这是我第一次使用这个宝石。我知道如何根据模型创建文件,但我不知道如何匹配两个。

我有一个意见\参与者\索引:

<%= link_to 'Download CSV', '/participants.csv' %>

控制器:

def index
 @participants = Participant.all
 respond_to do |format|
   format.html # index.html.erb
   format.json { render json: @participants }
   format.csv  { send_data @participants.to_comma }
 end
end

参与者型号:

require 'comma'
class Participant < ActiveRecord::Base
  comma do
    id
    token
  end
end

和字段模型:

require 'comma'
class Field < ActiveRecord::Base
  comma do
   name
   value
   id_participant
  end
end

在数据库中我有:

Participant1 = ["id" => 1 , "token" => "a"]
Participant2 = ["id" => 2 , "token" => "b"] 
Field1= ["id_participant" => 1, "name" => "p1_exams1", "value" =>5]
Field2= ["id_participant" => 1, "name" => "p1_exams2", "value" =>3]
Field3= ["id_participant" => 2, "name" => "p2_exams1", "value" =>2]
Field4= ["id_participant" => 2, "name" => "p2_exams2", "value" =>3]

我想要一个这样的文件:

id   token
 1     a

id_p  name            value
 1   p1_c1_exams1      5
 1   p1_c1_exams2      3

id   token
 2     b

id_p  name            value
 2   p1_c1_exams1      2
 2   p1_c1_exams2      3    

我在控制器中尝试了这个:

def index
@participants = Participant.all
@fields = Field.all
require 'csv'
csv_string = CSV.generate do |csv|
    @participants.each do |p|
        csv << ["id","token","last_ip_address","start_date","last_transition_date","completion_date","completed","total_time_survey","created_at"]
        csv << [ p.id, p.token , p.last_ip_address, p.start_date, p.last_transition_date, p.completion_date, p.completed, p.total_time_survey, p.created_at]
        @fields.each do |f|
            if String(f.id_participant) == String(p.id)
                csv << ["id","name","value","id_participant","id_survey","created_at"]
                csv << [f.id,f.name, f.insert_value, f.id_participant, f.id_survey, f.created_at]
            end
        end
    end
end


respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @participants }
  format.csv  { send_data csv_string,
    :type => "text/csv; charset=iso-8859-1; header=present",
    :disposition => "attachment; filename=Database.csv" }
end
end
4

1 回答 1

4

您也可以为此使用 fastercsv 我认为这将帮助您了解您在参与者和字段之间有很多关系我已经编写了一些代码您可以根据需要对其进行自定义

@participants = Participant.all
  csv_string = FasterCSV.generate do |csv|
     @participants.each do |i|
     csv << ["id","token"]
     csv << [ i.id, i.token ]
     i.fields.each do |j|
      csv << ["id_p","name", "value"]
      csv << [i.id,j.name, j.value]
     end
     end
     end
 send_data csv_string,
          :type => "text/csv; charset=iso-8859-1; header=present",
          :disposition => "attachment; filename=anyName.csv"
于 2012-11-16T10:53:12.467 回答