簡體   English   中英

調用rake任務時無法加載命名空間模型

[英]Cannot load namespaced model when invoking rake task

我有一個rake任務調用其他rake任務,所以我的開發數據可以很容易地重置。

第一個rake任務(lib / tasks / populate.rake)

# Rake task to populate development database with test data
# Run it with "rake db:populate"
namespace :db do
  desc 'Erase and fill database'
  task populate: :environment do
    ...
    Rake::Task['test_data:create_company_plans'].invoke
    Rake::Task['test_data:create_companies'].invoke
    Rake::Task['test_data:create_users'].invoke
   ...
  end
end

第二個rake任務(lib / tasks / populate_sub_scripts / create_company_plans.rake)

namespace :test_data do
  desc 'Create Company Plans'
  task create_company_plans: :environment do
    Company::ProfilePlan.create!(name: 'Basic', trial_period_days: 30, price_monthly_cents: 4000)
    Company::ProfilePlan.create!(name: 'Professional', trial_period_days: 30, price_monthly_cents: 27_500)
    Company::ProfilePlan.create!(name: 'Enterprise', trial_period_days: 30, price_monthly_cents: 78_500)
  end
end

當我運行bin / rake db:populate然后我得到這個錯誤

耙子流產了! LoadError:無法自動加載常量Company :: ProfilePlan,預期/home/.../app/models/company/profile_plan.rb來定義它

但是當我獨立運行第二個rake任務時,它運行良好。

模型(路徑:/home/.../app/models/company/profile_plan.rb)

class Company::ProfilePlan < ActiveRecord::Base
  # == Constants ============================================================

  # == Attributes ===========================================================

  # == Extensions ===========================================================
  monetize :price_monthly_cents

  # == Relationships ========================================================
  has_many :profile_subscriptions

  # == Validations ==========================================================

  # == Scopes ===============================================================

  # == Callbacks ============================================================

  # == Class Methods ========================================================

  # == Instance Methods =====================================================
end

Rails 5.0.1 Ruby 2.4.0

該應用程序剛剛從4.2升級到5

它在我需要整個路徑時起作用:

require "#{Rails.root}/app/models/company/profile_plan.rb"

但這對我來說似乎很奇怪,因為在錯誤消息中,rails具有到Model的正確路徑。 有人知道為什么我從另一個rake任務調用時需要該文件嗎?

非常感謝你

好吧,看起來rake並不急於加載,所以當你單獨調用create_company_plans.rake它會加載引用的對象,但是當你從另一個rake調用它時,它不知道你需要它們所以它們不是加載。

您可以查看與您類似的其他QA

我想也許你不需要整條路徑,只需:

require 'models/company/profile_plan'

根據我的理解,你可以通過reenable然后revoke任務來解決問題,如下所示。 請原諒我,如果這不起作用。

['test_data:create_company_plans', 'test_data:create_companies'].each do |task|
  Rake::Task[task].reenable
  Rake::Task[task].invoke
end

有關此stackoverflow問題的更多信息, 如何從rake-task中運行rake-tasks

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM