这是我第一次将csv文件导入我的rails应用程序。
我在/lib/tasks/import.rake
中有以下代码 require 'csv'
CSV.foreach("lib/articles.csv", headers: true, encoding: "ISO8859-1") do |row|
Article.new(title: row["Title"], body: row["Body"], user: User.find(1))
end
当我运行rake import:articles
我收到此错误:
NameError: uninitialized constant Article
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:8:in `block in <top (required)>'
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:7:in `<top (required)>'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `block in run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `each'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/application.rb:452:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:453:in `load_tasks'
/Users/justinMgrant/code/hrsurvival/Rakefile:6:in `<top (required)>'
(See full trace by running task with --trace)
知道我做错了什么吗?
答案 0 :(得分:1)
问题是你实际上并没有在rakefile中定义你的任务。这应该可以让您运行rake import:articles
。
namespace :import do
desc 'An optional description for what the task does'
task :articles => :environment do
# your code goes here
end
end
rake import:articles
说要在名为articles
的名称空间中查找名为import
的任务,这就是为什么名称空间对于您当前正在尝试的内容所必需的。
正如@max所提到的,利用task :articles => :environment
告诉任务在Rails环境的上下文中运行,这将使您的Articles
模型和任何其他模型可用于该任务