2016-07-24 49 views
0

我试图创建使用服务的rake任务。在该服务中,我想在我的数据库中加载最后保存的MonthlyMetrics表记录。尝试引用服务中的数据库记录时未初始化的常量错误

在我耙文件:

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 

而且我MetricsServicelib/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命名空间中的一个类.. ..?这不是像我试图将MonthlyMetric定义为嵌套类MetricsService ...我只是试图将其称为ActiveRecord查询。

我在同一目录下的其他服务中完成了其他ActiveRecord查询,例如User

我在这里做错了什么?

回答

1

我认为如果你只是将=> :environment添加到你的rake任务的末尾,那可能会解决这个问题。

如:

task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] => :environment do

我碰到类似的问题在那里没有这个上涨到每个耙任务Rails的不初始化正确的环境。

+1

你完全正确!尽管环境应该在任务数组内,否则它会在散列火箭上抛出一个错误。 – Doug

相关问题