ruby 3.2.8 アプリケーションでコンマ gem を使用して 2 つのモデルを含む 1 つの CSV ファイルを作成したいと考えています。質問に対する答えは些細なことかもしれませんが、この宝石を使用するのはこれが初めてです。モデルに基づいてファイルを作成する方法は知っていますが、2 つの一致を作成する方法はわかりません。
私はビュー\参加者\インデックスを持っています:
<%= 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