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

基本上,我能做的是:-

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

当前回答

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

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

或更短:

ApplicationRecord.descendants.collect(&:name)

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

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
Module.constants.select { |c| (eval c).is_a?(Class) && (eval c) < ActiveRecord::Base }

以下是一个经过复杂Rails应用程序(支持Square的应用程序)审查的解决方案

def all_models
  # must eager load all the classes...
  Dir.glob("#{RAILS_ROOT}/app/models/**/*.rb") do |model_path|
    begin
      require model_path
    rescue
      # ignore
    end
  end
  # simply return them
  ActiveRecord::Base.send(:subclasses)
end

它采用了这篇文章中最好的答案,并将它们组合成最简单、最彻底的解决方案。当你的模型在子目录中时,可以使用set_table_name等。

万一有人无意中发现了这个问题,我有另一个解决方案,不依赖于dir读取或扩展Class类……

ActiveRecord::Base.send :subclasses

这将返回一个类数组。所以你可以这样做

ActiveRecord::Base.send(:subclasses).map(&:name)

可以检查一下

@models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize}