我有一个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然后我得到这个错误
rake aborted! LoadError: Unable to autoload constant
Company::ProfilePlan, expected
/home/…/app/models/company/profile_plan.rb to define it
但是当我独立运行第二个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'