Rake中模型引用的未初始化常量错误

时间:2011-07-07 05:40:12

标签: ruby-on-rails-3 model rake

在我的sample_data.rake文件中,我有“Diner.create!(...)”命令导致“uninitialized constant Diner”错误。但是,如果我在Rails控制台中执行相同的“Diner.create!(...)”命令,则表示成功。如果我在sample_data.rake文件中“需要”该模型,则会收到错误“ActiveRecord::ConnectionNotEstablished”,其中回溯显示为“active_record/connection_adapters/abstract/connection_pool.rb:318:in retrieve_connection'”。这是我的diner.rb文件:

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

sample_data.rake文件中导致问题的代码是:

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

删除上述代码会导致文件成功处理。而且,正如我之前所说,上面的代码在rails控制台中正常工作。

1 个答案:

答案 0 :(得分:9)

您的rake任务显然缺少rails环境。 如果您的任务具有以下结构且您的模型在$LOAD_PATH范围内,那么一切都应该没问题:

     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

你看到task :populate => :environment do行,它告诉rake启动环境任务[1],然后执行你现在可以访问模型和数据库的任务

[1] railties-3.0.4 / LIB /轨道/ application.rb中#214

[1] railties-3.0.4 / LIB /轨道/ application.rb中#101

欢呼声