尝试引用服务中的数据库记录时出现未初始化的常量错误
Uninitialized constant error when trying to refer to a database record within a service
我正在尝试创建一个使用服务的 rake 任务。在该服务中,我想在我的数据库中加载 MonthlyMetrics
table 的最后保存记录。
在我的 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
定义为嵌套的 class within MetricsService
...我只是想引用它作为 ActiveRecord 查询。
我在同一目录的其他服务中完成了其他 ActiveRecord 查询,例如 User
。
我做错了什么?
我认为如果您只是将 => :environment
添加到您的 rake 任务的末尾,这可能会解决问题。
如:
task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] => :environment do
我 运行 遇到了类似的问题,其中 Rails 没有初始化正确的环境,而没有将其附加到每个 rake 任务。
我正在尝试创建一个使用服务的 rake 任务。在该服务中,我想在我的数据库中加载 MonthlyMetrics
table 的最后保存记录。
在我的 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
定义为嵌套的 class within MetricsService
...我只是想引用它作为 ActiveRecord 查询。
我在同一目录的其他服务中完成了其他 ActiveRecord 查询,例如 User
。
我做错了什么?
我认为如果您只是将 => :environment
添加到您的 rake 任务的末尾,这可能会解决问题。
如:
task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] => :environment do
我 运行 遇到了类似的问题,其中 Rails 没有初始化正确的环境,而没有将其附加到每个 rake 任务。