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

基本上,我能做的是:-

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

当前回答

ActiveRecord:美国:基地connection。表

其他回答

ActiveRecord::Base.connection.tables.map do |model|
  model.capitalize.singularize.camelize
end

将返回

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

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

model.classify.constantize.attribute_names

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

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

或更短:

ApplicationRecord.descendants.collect(&:name)

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

Rails.application.eager_load!

我还不能评论,但我认为sj26的答案应该是首要答案。提示一下:

Rails.application.eager_load! unless Rails.configuration.cache_classes
ActiveRecord::Base.descendants

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

对于快速加载,请尝试:

Zeitwerk::Loader.eager_load_all

Then

ApplicationRecord.descendants

确保在调用后代之前加载你的应用程序,这样所有的类都被加载了:

Rails.application.eager_load! unless Rails.application.config.eager_load

ApplicationRecord.descendants.each do |clazz|
  # do something with clazz, e.g. User, Event, Attendance, etc.
end