2012-11-16 25 views
1

我想在我的ruby 3.2.8應用程序中創建一個包含逗號爲寶石的兩個模型的CSV文件。也許這個問題的答案是微不足道的,但這是我第一次使用這個寶石。我知道如何根據模型創建文件,但我不知道如何匹配兩個文件。如何用逗號創建一個包含兩個模型的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 

在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 

回答

4

你也可以使用更快的速度爲這個 我認爲這將有助於你我的理解是你有很多參與者和場之間的關係r egarding這我寫了一些代碼ü可以定製它,因爲你需要

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

我現在試試,謝謝!但是,我是否將這些代碼放入cotroller?和觀點的呼喚,它是如何完成的?在模型中不得不放置一些說明? –

+0

您可以將其添加到控制器。抱歉,我遺漏了一些基本部分發送csv發生後的數據現在我已經對我的解決方案進行了更改 – kunnu

+0

ehm,我有問題:請切換到Ruby 1.9的標準CSV庫。它的速度更快,支持Ruby 1.9的m17n編碼引擎。但我有1.9.3 Ruby和3.2.8 Rails ... –

相關問題