2

This is my first time importing a csv file to my rails app.

I have the code below in /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

When I run rake import:articles

I get this error:

     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)

Any idea what I’m doing wrong?

jeffdill2
  • 3,968
  • 2
  • 30
  • 47
jgrant
  • 582
  • 6
  • 20
  • 3
    Add the complete rake task please. I'm guessing that you are not using `task :taskname => :environment` which creates the rake task in the context of your Rails environment. http://stackoverflow.com/questions/7044714/whats-the-environment-task-in-rake – max Feb 24 '16 at 19:26
  • That's what I have in the rake task, but when I add `task articles: :environment` this error appears `Don't know how to build task 'import:articles' (see --tasks)` – jgrant Feb 24 '16 at 19:31
  • That's the entirety of your rake file? – jeffdill2 Feb 24 '16 at 19:32

1 Answers1

1

The problem is that you're not actually defining your task in your rakefile. This should work for you to be able to run 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 is saying to look for a task called articles within a namespace called import, which is why the namespace is necessary for what you're currently trying.

And as @max mentioned, utilizing task :articles => :environment is what tells the task to run in the context of your Rails environment, which would make your Articles model and any other model available to you in that task.

jeffdill2
  • 3,968
  • 2
  • 30
  • 47