0

如何在 rails 应用程序之外以正确的顺序加载/要求我的 activerecord 模型。我有许多 STI 模型,但我得到一个未初始化的常量异常。

$:.push File.expand_path("../../../app/models", __FILE__)
require "active_record"

Dir["#{File.expand_path('../../../app/models', __FILE__)}/*.rb"].each do |path|
  require "#{File.basename(path, '.rb')}"
end

我有很多工作需要使用 resque 运行,我不想每次都加载我的 rails 应用程序并部署到所有工作机器

编辑:还有一点要澄清。有两个项目一个 Rails 项目和一个包含我的模型的 Rails 引擎项目。我不使用我的 resque 作业加载 rails 引擎本身,我只是在一个单独的类中使用上面的代码片段来加载模型上的活动记录。这一直有效,直到我添加了一些 STI 模型,由于命名导致子项尝试在父项之前加载。rails 引擎项目在 rails 项目中加载得很好,没有问题,这只是因为我试图在 rails 项目之外使用活动记录。

4

3 回答 3

3

A very simple solution if you don't want to autoload is to require the base class in the children classes. Explicitly requiring dependencies is a good thing. :)

app/models/profile.rb

class Profile < ActiveRecord::Base
end

app/models/student.rb

require 'models/profile'

class Student < Profile
end

app/models/teacher.rb

require 'models/profile'

class Teacher < Profile
end
于 2015-04-27T19:24:36.960 回答
2

模型将在首次提及时自动加载。因此,只需以适当的顺序将它们命名为某个地方(例如,在 中config/initializers/load_order.rb):

Product
LineItem
Cart

并检查它是否有帮助。

于 2012-04-24T20:21:22.750 回答
-1

我解决了我的问题。可能有更好的方法,但这对我有用。

basedir = File.expand_path('../../../app/models', __FILE__) 
Dir["#{basedir}/*.rb"].each do |path|
  name = "#{File.basename(path, '.rb')}"
  autoload name.classify.to_sym, "#{basedir}/#{name}"
end
于 2012-04-25T15:51:36.827 回答