如何强制 Rails 加载所有模型?
Rails 按需加载模型。对于我正在编写的 rake 任务,我需要能够迭代所有 ActiveRecord::Base
实例(这可以通过 ActiveRecord::Base.send(:subclasses)< /代码>)。
然而,为了使上述工作正常,它们必须已经被加载。有人知道强制加载所有模型的方法吗?理想情况下,我不想浏览 app/models
因为我也想捕获插件添加的模型。
Rails does model loading on demand. For a rake task that I'm writing, I need to be able to iterate over all ActiveRecord::Base
instances (which is possible with ActiveRecord::Base.send(:subclasses)
).
However, for the above to work, they have to already be loaded. Anyone know of a way to force all models to load? Ideally I'd like to not have to poke through app/models
since I'd like to catch models added by plugins as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我需要为 rake 任务加载所有模型来检查所有记录的有效性,并找到了方便的方法
eager_load< /code>
,可以像这样简单地使用:
Rails.application.eager_load!
I needed all models loaded for a rake task that checks the validity of all records, and found the handy method
eager_load
, which can be used simply like so:Rails.application.eager_load!
导轨 2:
导轨 3:
另一种方式:
rails 2:
rails 3:
another way:
Rails 7.0
实际上会加载所有模型以及您可能需要的任何内容。
也适用于
.rake
文件(rails cli 命令)。rails 7.0
Will actually load all the models and anything you could need.
Works fine for
.rake
files (rails cli commands) too.