I have tried to import a CSV file into ruby on rails using many scripts and methods and nothing seems to work. I have been hoping that code from Erik on Rails blog will help to get my job done.
I put this script into lib/tasks/import.rake:
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model, :needs] => [:environment] do |task,args|
lines = File.new(args[:filename]).readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
values = line.strip.split(',')
attributes = Hash[keys.zip values]
Module.const_get(args[:model]).create(attributes)
end
end
I created a model in the rails console
rails generate model SomeModel
then ran this in the rails console
rake csv_model_import[somefile.csv,SomeModel]
After running this, the cursor just returns in the console. It fails silently. When viewing the database file for the rails program, the table is empty after the import. It has filed to import the data.
I tried something else as well. I tried first creating a model with the fields and types defined before running the rake import command. This also failed in the same way.
I am very new to Ruby on Rails and I am. I have spent 2 days trying to get a CSV file into Ruby on Rails and would greatly appreciate some help. Please let me know how to proceed, Thanks so much guys.