Rake 中模型参考上未初始化的常量错误
在我的sample_data.rake 文件中,我的命令“Diner.create!(...)
”会导致“未初始化的常量Diner
”错误。但是,如果我在 Rails 控制台中执行相同的“Diner.create!(...)”命令,则会成功。如果我“需要”sample_data.rake 文件中的模型,则会收到错误“ActiveRecord::ConnectionNotEstablished
”,回溯显示“active_record/connection_adapters/abstract/connection_pool.rb:318” :在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 控制台中可以正常工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 rake 任务显然缺少 Rails 环境。
如果您的任务具有以下结构并且您的模型位于
$LOAD_PATH
内,那么一切都应该没问题:您会看到
task :populate =>; :environment do
行,它告诉 rake 启动环境任务[1],然后执行您的任务,该任务现在可以访问您的模型和数据库[1]railties-3.0.4/lib/rails/application .rb#214
[1]railties-3.0.4/lib/rails/application.rb#101
干杯
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: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