【问题标题】:Uninitialized constant error when trying to refer to a database record within a service尝试引用服务中的数据库记录时出现未初始化的常量错误
【发布时间】:2016-07-24 22:34:02
【问题描述】:

我正在尝试创建一个使用服务的 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

还有我在lib/metrics_service.rb 内的MetricsService

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 定义为嵌套类 within MetricsService... 我只是试图将其称为 ActiveRecord 查询。

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

我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails namespaces rake


    【解决方案1】:

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

    如:

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

    我遇到过类似的问题,Rails 没有在每个 rake 任务上附加此设置,就无法初始化正确的环境。

    【讨论】:

    • 你完全正确!尽管环境应该在任务数组中,否则它会在哈希火箭上抛出错误。
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-03-02
    相关资源
    最近更新 更多