是否有一种方法可以获得Rails应用程序中所有模型的集合?
基本上,我能做的是:-
Models.each do |model|
puts model.class.name
end
是否有一种方法可以获得Rails应用程序中所有模型的集合?
基本上,我能做的是:-
Models.each do |model|
puts model.class.name
end
当前回答
以下是一个经过复杂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等。
其他回答
是的,有很多方法可以找到所有的模型名称,但我在我的gem model_info中所做的是,它会给你所有的模型,甚至包括在gems中。
array=[], @model_array=[]
Rails.application.eager_load!
array=ActiveRecord::Base.descendants.collect{|x| x.to_s if x.table_exists?}.compact
array.each do |x|
if x.split('::').last.split('_').first != "HABTM"
@model_array.push(x)
end
@model_array.delete('ActiveRecord::SchemaMigration')
end
然后打印出来
@model_array
万一有人无意中发现了这个问题,我有另一个解决方案,不依赖于dir读取或扩展Class类……
ActiveRecord::Base.send :subclasses
这将返回一个类数组。所以你可以这样做
ActiveRecord::Base.send(:subclasses).map(&:name)
def load_models_in_development
if Rails.env == "development"
load_models_for(Rails.root)
Rails.application.railties.engines.each do |r|
load_models_for(r.root)
end
end
end
def load_models_for(root)
Dir.glob("#{root}/app/models/**/*.rb") do |model_path|
begin
require model_path
rescue
# ignore
end
end
end
Rails5的模型现在是ApplicationRecord的子类,所以要获得应用程序中所有模型的列表,你需要:
ApplicationRecord.descendants.collect { |type| type.name }
或更短:
ApplicationRecord.descendants.collect(&:name)
如果你在开发模式下,你需要在以下情况之前加载模型:
Rails.application.eager_load!
在Rails 6中,Zetiwerk成为默认的代码加载器。
对于快速加载,请尝试:
Zeitwerk::Loader.eager_load_all
Then
ApplicationRecord.descendants