I am new to ruby on rails and I am having trouble in exporting the data to csv. I have followed the following video:
https://medium.com/coderaga/rails-import-export-csv-data-without-gem-fbf2a36a84f6
I have put require 'csv' in application.rb file also.
My student.rb model has:
def self.to_csv(fields = column_names, options = {})
CSV.generate(options) do |csv|
csv << fields
all.each do |student|
csv << student.attributes.values_at(*fields)
end
end
end
My students_controller has following:
def index
@students=Student.all
puts @students
respond_to do |format|
format.html
format.csv{send_data @students.to_csv(['UIN', 'Name' ,'Section', 'Attempts', 'Score'])}
end
end
I think the all.each statement is empty as when I am doing puts student.attributes.values_at(*fields)
, there is nothing so that is why there is nothing being written. But I am not sure how can I fix it.
Student Load (0.3ms) SELECT "students".* FROM "students"
#<Student:0x007f9a2386ddb8>
#<Student:0x007f9a2386dc78>
#<Student:0x007f9a2386db38>
CACHE Student Load (0.0ms) SELECT "students".* FROM "students"
Please help
Aucun commentaire:
Enregistrer un commentaire