如何使用逗号gem创建一个包含两个模型的CSV文件?

时间:2012-11-16 08:35:58

标签: ruby-on-rails ruby ruby-on-rails-3 fastercsv

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

我有一个views \ participant \ index:

<%= 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

在db中我有:

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

1 个答案:

答案 0 :(得分:4)

您也可以使用fastercsv 我认为这将有助于你理解你在参与者和Field之间有很多关系,我已经写了一些代码你可以根据需要定制它

@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"