【发布时间】:2017-05-30 15:41:57
【问题描述】:
我有一个调用其他 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 中止! LoadError:无法自动加载常量 公司::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
导轨 5.0.1 Ruby 2.4.0
应用刚刚从 4.2 升级到 5
当我需要整个路径时它可以工作:
require "#{Rails.root}/app/models/company/profile_plan.rb"
但这对我来说似乎很奇怪,因为在错误消息中 rails 具有模型的正确路径。有人知道为什么在从另一个 rake 任务调用时我必须要求该文件吗?
非常感谢
【问题讨论】:
-
但是你有
/home/.../app/models/company/profile_plan.rb对吗? -
@MikDiet,谢谢。是的,我将它们添加到我的问题中
-
尝试定义公司模块
module Company class ProfilePlan < ... -
@taro,谢谢你的想法,我之前也试过这个,但我得到:TypeError:Company is not a module 我想这是因为我也有一个名为Company的模型
标签: ruby-on-rails ruby ruby-on-rails-5 rake-task