读取 Rails 应用程序中的所有模型 [英] Reading all models in a Rails application
问题描述
有没有办法检测 Rails 应用程序中使用的所有具有数据库表的模型?我试图通过读取 app/models 目录中的所有模型并简单地读取该目录中的所有文件来检测 Rails 应用程序中的所有模型.但是,我认为这不是最好的方法,并且花了大量时间对此进行研究,但我还没有得到更好的答案.谁能帮我这个.非常感谢!
Is there a way to detect all the models used in a Rails app that have database tables? I've tried to detect all models in a Rails application by reading all the models off of the app/models directory and simply read all the files in that directory. However, I do not think this is the best approach and have spent a considerable amount of time researching this but I haven't gotten a better answer yet. Can anyone help me with this. Many thanks!
推荐答案
我假设您正在使用 ActiveRecord.如果是,请按照以下步骤获取所有 ActiveRecord::Base 子类的列表:
I'm assuming you are using ActiveRecord. If you are, here is how you go about getting a list of all ActiveRecord::Base subclasses:
ActiveRecord::Base.subclasses
您还可以执行以下操作:
You can also do the following:
dbmodels = []
ObjectSpace.each_object(Module){ |m| dbmodels << m if m.ancestors.include?(ActiveRecord::Base) && m != ActiveRecord::Base }
dbmodels
现在应该包含所有 ActiveRecord::Base 模型.
dbmodels
should now contain all your ActiveRecord::Base models.
请记住,在您的开发环境中,除非已加载/使用子类,否则您不会获得完整的子类列表,因此我建议您在生产环境中执行此操作,这样您就可以确保所有模型已加载.
Keep in mind that in your development environment you won't get a full list of subclasses unless they have been loaded/used, so I would recommend performing this in your production environment instead, that way you can ensure that all your models have been loaded.
这篇关于读取 Rails 应用程序中的所有模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!