1
루비 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
나는 고마워! 하지만이 코드를 cotroller에 넣을 수 있습니까? 그리고보기의 부름, 그것이 어떻게 이루어 졌는가? 모델에서 몇 가지 지시 사항을 넣어야합니까? –
이것을 컨트롤러에 추가 할 수 있습니다. 미안 해요 일부 CSV genearation 후 데이터를 보낼 기본 부분을 놓친 지금 나는 내 솔루션을 변경했습니다 – kunnu
흠, 나는 문제가 : 루비 1.9의 표준 CSV 라이브러리로 전환하십시오. FasterCSV와 Ruby 1.9의 m17n 인코딩 엔진을 지원합니다. 하지만 1.9.3 루비와 3.2.8 레일즈를 가지고 있습니다 ... –