Jack R-G
Jack R-G

Reputation: 1906

Uninitialized Constant error on Model reference in Rake

In my sample_data.rake file, I have the command "Diner.create!(...)" which causes an "uninitialized constant Diner" error. However, if I execute the same "Diner.create!(...)" command in the Rails console, it is successful. If I "require" the model in the sample_data.rake file, I get the error "ActiveRecord::ConnectionNotEstablished" with the backtrace showing "active_record/connection_adapters/abstract/connection_pool.rb:318:in retrieve_connection'". Here is my diner.rb file:

class Diner < ActiveRecord::Base
  has_many  :redemptions
  has_many  :surveys, :through => :redemptions
end

And the code in the sample_data.rake file that causes the problem is:

99.times do |n|
  gender = rand(1) == 0 ? "male" : "female"
  birthdate = Date.ordinal(DateTime.now.year - 13 - rand(62), rand(364)+1)
  Diner.create!(:gender => gender, :birthdate => birthdate)
end

Removing the above code causes the file to process successfully. And, as I said earlier, the above code works correctly in rails console.

Upvotes: 3

Views: 4012

Answers (1)

krichard
krichard

Reputation: 3694

Your rake task is clearly missing the rails environment. If your task has the following structure and your model is within $LOAD_PATH then everything should be fine:

     namespace :yourapp do
         desc "Create sample data"
         task :populate => :environment do
           # create other data
           99.times do |n|
             gender = rand(1) == 0 ? "male" : "female"
             birthdate = Date.ordinal(DateTime.now.year - 13 - rand(62), rand(364)+1)
             Diner.create!(:gender => gender, :birthdate => birthdate)
           end
         end
     end

You see that task :populate => :environment do line, it tells rake to fire up the environment task[1] and then perform your task which now has access to your models and the Database

[1]railties-3.0.4/lib/rails/application.rb#214

[1]railties-3.0.4/lib/rails/application.rb#101

cheers

Upvotes: 9

Related Questions