是否有一种方法可以获得Rails应用程序中所有模型的集合?

基本上,我能做的是:-

Models.each do |model|
  puts model.class.name
end

当前回答

如果你只需要类名:

ActiveRecord::Base.descendants.map {|f| puts f}

只需在Rails控制台中运行它,仅此而已。好运!

编辑:@sj26是正确的,你需要在调用后代之前先运行这个:

Rails.application.eager_load!

其他回答

这对我很管用。特别感谢上面所有的帖子。这将返回所有模型的集合。

models = []

Dir.glob("#{Rails.root}/app/models/**/*.rb") do |model_path|
  temp = model_path.split(/\/models\//)
  models.push temp.last.gsub(/\.rb$/, '').camelize.constantize rescue nil
end

在Rails 6中,Zetiwerk成为默认的代码加载器。

对于快速加载,请尝试:

Zeitwerk::Loader.eager_load_all

Then

ApplicationRecord.descendants

Rails5的模型现在是ApplicationRecord的子类,所以要获得应用程序中所有模型的列表,你需要:

ApplicationRecord.descendants.collect { |type| type.name }

或更短:

ApplicationRecord.descendants.collect(&:name)

如果你在开发模式下,你需要在以下情况之前加载模型:

Rails.application.eager_load!
ActiveRecord::Base.connection.tables.map do |model|
  model.capitalize.singularize.camelize
end

将返回

["Article", "MenuItem", "Post", "ZebraStripePerson"]

附加信息如果你想在对象名上调用一个没有model:string未知方法或变量错误的方法,使用这个

model.classify.constantize.attribute_names

Rails 3、4和5的完整答案是:

如果cache_classes是关闭的(在开发中默认是关闭的,但在生产中是打开的):

Rails.application.eager_load!

然后:

ActiveRecord::Base.descendants

这将确保加载应用程序中的所有模型,无论它们位于何处,并且也加载了您使用的任何提供模型的gem。

这应该也适用于从ActiveRecord::Base继承的类,如Rails 5中的ApplicationRecord,并只返回后代的子树:

ApplicationRecord.descendants

如果您想了解更多关于这是如何完成的,请查看ActiveSupport:: descent stracker。