2012-01-11 4 views
0

가변 개수의 레코드로 된 CSV 내보내기 (레일에서, 루비로)를 만들고 있습니다. 레코드 당 내보내는 필드 수는 각 책의 저자 수에 따라 다릅니다. 사용자가 Excel과 같은 방식으로이 CSV를보고 지속적으로 데이터를 열로 볼 수 있기를 기대한다면 이는 이상적이지 않습니다.CSV 내보내기에서 가변 개수의 필드를 수용합니다.

# header-row for the data 
csv << ["column heading 1", "column heading 2", "column heading 3" #etc] 

Book.all do |book| 
    row_data = book.id 
    row_data << book.some_other_field # etc 
    book.authors.each do |author| 
    row_data << author.first.name 
    #etc 

답변

1

업데이트 : 나는 열 수를 설정할 수 있습니다 어떻게 CSV 빌더의 구조가이 같은 것을 주어, 블록이 반복됩니다 총 횟수 될 수 바보 같은 내게 질문을 오해.

나는 약간의 시간 동안 단순히 헤더를 작성하는 것을 지연 할 것이다. Prepend a single line to file with Ruby

당신은 당신의 저자의 최대 길이 다닐 필요가 : 루비는 사전 펜던하는 데이터를 파일에 능력이 내가 코드가 작동 희망

max_authors = 0  
Book.all do |book| 
    row_data = book.id 
    row_data << book.some_other_field # etc 
    if book.authors.count > max_authors 
    max_authors = book.authors.count 
    end 
    book.authors.each do |author| 
    row_data << author.first.name 
    #etc 

# header-row for the data 
a = (0..max_authors).collect { |n| "column heading #{n}" } 
csv << a.join(",") #obviously this has to be prepended 

을 .. 수 없음 그것을 테스트 ..하지만 당신은 아이디어를 얻을

+0

하, 나는 결코 생각하지! 우수한. – snowangel

관련 문제