# Using a Model in a rake task?

**URL:** <https://www.ruby-forum.com/t/using-a-model-in-a-rake-task/113438>\
**Category:** Rails\
**Created:** [August 31, 2007, 1:53am UTC](https://www.ruby-forum.com/t/using-a-model-in-a-rake-task/113438 "2007-08-31T01:53:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![chirag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@chirag](https://www.ruby-forum.com/u/chirag)\
**Post date:** [August 31, 2007, 1:53am UTC](https://www.ruby-forum.com/t/using-a-model-in-a-rake-task/113438/1 "2007-08-31T01:53:09Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![chirag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@chirag](https://www.ruby-forum.com/u/chirag)\
**Post date:** [August 31, 2007, 2:07am UTC](https://www.ruby-forum.com/t/using-a-model-in-a-rake-task/113438/2 "2007-08-31T02:07:49Z")

</div>

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](http://blog.hasmanythrough.com)
