Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top