0

Model contact.rb:

class Contact < ActiveRecord::Base
  attr_accessible :name, :phone
end

Test.rb:

Contact.create({:name => "Josh", :phone => "123-456789"})

When I run test.rb from terminal I'm receiving the error:

lib/tasks/test.rb:1:in `': uninitialized constant Contact (NameError)

database.yml:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

I believe this is a trivial question. I've searched this forum, but it didn't give any clue on this.

Let me know if I have to input additional information to make it clear.

Askar
  • 5,784
  • 10
  • 53
  • 96

1 Answers1

1

You cannot simply run ruby lib/tasks/test.rb because the Rails environment will not be loaded. To fix this, you need to use a rake task.

You first have to rename your file lib/tasks/test.rb to lib/tasks/test.rake.

Then, you need to add this to test.rake.

namespace :contact do # This is not require. It can work without having to nest your task within a namespace.
  desc 'Add contact'
  task 'add' => [:environment]  do #Here, we specify we want to load the environment
    Contact.create({:name => "Josh", :phone => "123-456789"})
  end
end

Then, run rake -T which will list all the available tasks.

You will be able to launch your task with rake contact:add.

To schedule your task to be run at a specific time, you might want to take a look at the Whenever gem.

Hope it helps.

Arkan
  • 6,196
  • 3
  • 38
  • 54
  • thanks, I'm aware of the Whenever gem. When I run following your advice above I've received the error: rake aborted! uninitialized constant Inflector /home/askar/Dropbox/rails_studio/sqltest/config/environment.rb:7:in `' /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/railties-3.2.13/lib/rails/application.rb:103:in `require' /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/railties-3.2.13/lib/rails/application.rb:103:in `require_environment!' ... I couldn't put all the error message as it is long. – Askar Jun 18 '13 at 09:03
  • What do you have in config/environment.rb ? Any custom statement ? – Arkan Jun 18 '13 at 09:10
  • Oh, sorry, I had a custom statement there, before I made this post. Once I've delete it, it worked. Thanks a lot! :) – Askar Jun 18 '13 at 09:11