creating rake task for importing data from csv file

江枫思渺然 提交于 2019-12-12 04:43:03

问题


I am creating a rake task to import csv file data to my database (MySQL). Here is what I did but It is not working

require 'csv'
namespace :tech do                                                                                                                                          

desc "Import tech from csv file"

task temp: :environment do

file = "tech.csv"

CSV.foreach(file, :headers => true) do |row|
  Temp.create ({
                         :current => row[1],
                         :today => row[2],
                         :week=> row[3],
                         :month => row[4]
                       })
end

end end

but when I run rake tech:temp it throws this error

Don't know how to build task 'tech:temp'
y/gems/2.0.0/gems/rake-10.3.2/lib/rake/task_manager.rb:62:in `[]'
/p353/lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:149:in `invoke_task'
lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `block (2 levels) in    top_level'
 /lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `each'

 /lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `block in top_level'

 /lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:115:in `run_with_threads'

  /lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:100:in `top_level'
  lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:78:in `block in run'
  /lib/ruby/gems/2.0.0/gems/rake-10.3.2/lib/rake/application.rb:176:in ` standard_exception_handling'
  lib/rake/application.rb:75:in `run'
  /ruby/gems/2.0.0/gems/rake-10.3.2/bin/rake:33:in `<top (required)>'
  bin/rake:23:in `load'
  /bin/rake:23:in `<main>'

I already have Temp model existing and respective table in database after migration


回答1:


I was having the same issue while writing rake task to populate data in database. In my case the error was same and it was nothing just running the rake task in wrong manner.

I guess you are doing the same, as per the error I can guess

You are running rake tech:temp in which task is temp and namespace is tech, which is wrong you should pass it other was as first you need to give task name then namespace.

so the right command is

rake temp:tech

It hope this will work. It is silly I know



来源:https://stackoverflow.com/questions/26212250/creating-rake-task-for-importing-data-from-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!