Using a Model in a rake task?

I’'m trying to use a model in a Rake task like this:

require ‘time’

namespace :halo do
desc "post to the usertable via "
task :post_user_with_activerecord do
end_time = Time.new
start_time = end_time - 60
until start_time > end_time
start_time = start_time + 15
heartrate = User.new(:user_id => 817, :timestamp =>
start_time, :value=> rand(5)+70)
heartrate.save
end
end
end

But I get the following error
rake aborted!
uninitialized constant User

When I add require ‘User’, I get an error saying uninitialized
constant ActiveRecord. When I add require ‘active_record’, I get
another error.

Is there something obvious that I’m missing?

chirag wrote:

I’'m trying to use a model in a Rake task like this:

require ‘time’

namespace :halo do
desc "post to the usertable via "
task :post_user_with_activerecord do
end_time = Time.new
start_time = end_time - 60
until start_time > end_time
start_time = start_time + 15
heartrate = User.new(:user_id => 817, :timestamp =>
start_time, :value=> rand(5)+70)
heartrate.save
end
end
end

But I get the following error
rake aborted!
uninitialized constant User

When I add require ‘User’, I get an error saying uninitialized
constant ActiveRecord. When I add require ‘active_record’, I get
another error.

Is there something obvious that I’m missing?

Yes. Well, simple if not obvious. You need to depend on the
:environment task.

task :post_user_with_activerecord => :environment do

That will give you access to all the classes in the app’s environment.


Josh S.
http://blog.hasmanythrough.com