是否有一种方法可以获得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!

其他回答

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

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

刚刚看到这个,因为我需要打印所有模型的属性(基于@Aditya Sanghi的评论):

ActiveRecord::Base.connection.tables.map{|x|x.classify.safe_constantize}.compact.each{ |model| print "\n\n"+model.name; model.new.attributes.each{|a,b| print "\n#{a}"}}

假设所有模型都在app/models中,并且你的服务器上有grep和awk(大多数情况下),

# extract lines that match specific string, and print 2nd word of each line
results = `grep -r "< ActiveRecord::Base" app/models/ | awk '{print $2}'`
model_names = results.split("\n")

它比Rails.application.eager_load快!或者用Dir遍历每个文件。

编辑:

这种方法的缺点是它忽略了间接继承自ActiveRecord的模型(例如FictionalBook < Book)。最可靠的方法是Rails.application.eager_load!;ActiveRecord::Base.descendants.map(&:name),尽管它有点慢。

以下是一个经过复杂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等。

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

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