简体   繁体   中英

How to add an array of records to row from active-record model in a CSV export file in rails

I am trying to add records to a row from an active-record model.

The CSV row is:

csv << [ "Question_name", "Question_description" ]

I am having an answer model which contain name attribute. I want to take all the anwer.name from Answer model and append it to the CSV row. so that the CSV row becomes:

csv << [ "Question_name", "Question_description", "ans1", "ans2", "ans3" ]

I tried to fix the issue and got the following code:

answers = Answer.all
answers.each {|a| ab << a.name }
data = ab.inject(" ") { |x,n| x << "#{n} " }
data.gsub!(/\s/,',')
csv << [ "Question_name", "Question_description", "#{data}" ]

But all the answer.name records were appended in one cell. Please help me to add the answer.name records in different columns

I believe you are looking to acheive this?

answers = Answer.all
row = ["Question_name", "Question_description"] + answers.map(&:name)
csv << row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM