Reputation: 167
I am making an application in Ruby on Rails which will ask users multiple choice questions. I want to upload questions to the database from an excel file. How can I do it?
Upvotes: 2
Views: 1355
Reputation: 9764
Save the Excel spreadsheet as a CSV file then use a CSV parser, perhaps in a rake file:
In lib/taks/import.rake:
require 'fastercsv'
namespace :import => :environment do
task :questions do
FasterCSV.foreach("path/to/file.csv") do |row|
q = Question.create(:question=>row[0], etc...)
PossibleAnswer.create(:question=>q, :answer=>row[1], etc....) #providing PossibleAnswer belongs_to Question
end
end
end
Then run "rake import:questions"
Upvotes: 4
Reputation: 32943
You could use the spreadsheet gem to read in the data from an excel file: http://rubygems.org/gems/spreadsheet
This is most useful if you want to allow users to upload their own excel documents, to import some questions, or if you want users to be able to download questions in excel file format.
If you just want to do a one-off import of some data i would go with Yule's idea and just do it via csv which is much easier to get to grips with.
Upvotes: 1