我正在尝试创建一个使用服务的 rake 任务。在该服务中,我想加载 MonthlyMetrics
的最后保存记录我的数据库中的表。
在我的 rake 文件中:
require 'metrics_service'
namespace :metrics do
@metrics_service = MetricsService.new
task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] do
puts "Donezo!"
end
# ...more cool tasks
end
还有我的
MetricsService
内lib/metrics_service.rb
:class MetricsService
def initialize
@metrics = MonthlyMetric.last
@total_customer_count = total_customers.count
assign_product_values
end
# Methods to do all my cool things...
end
每当我尝试运行类似
rake:db:migrate
的东西时,我收到以下错误:NameError: uninitialized constant MetricsService::MonthlyMetric
我不知道为什么它试图引用
MonthlyMetric
它是这样的......作为MetricsService
中的一个类(class)命名空间..?这不像我试图定义 MonthlyMetric
作为 MetricsService
中的嵌套类...我只是想将其称为 ActiveRecord 查询。我已经完成了其他 ActiveRecord 查询,例如
User
, 在同一目录内的其他服务中。我在这里做错了什么?
最佳答案
我想如果你只是添加 => :environment
到你的 rake 任务结束时,这可能会解决问题。
如:task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] => :environment do
我遇到过类似的问题,其中 Rails 没有初始化正确的环境,而没有将其附加到每个 rake 任务中。
关于ruby-on-rails - 尝试引用服务中的数据库记录时出现未初始化的常量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557491/