是否有一种方法可以获得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等。
其他回答
一行:Dir['app/models/\*.rb']。map {|f|文件。basename .camelize (f,“。*”)。constantize}
这对我很管用。特别感谢上面所有的帖子。这将返回所有模型的集合。
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
Dir.foreach("#{Rails.root.to_s}/app/models") do |model_path|
next unless model_path.match(/.rb$/)
model_class = model_path.gsub(/.rb$/, '').classify.constantize
puts model_class
end
这将为您提供项目上的所有模型类。
Rails5的模型现在是ApplicationRecord的子类,所以要获得应用程序中所有模型的列表,你需要:
ApplicationRecord.descendants.collect { |type| type.name }
或更短:
ApplicationRecord.descendants.collect(&:name)
如果你在开发模式下,你需要在以下情况之前加载模型:
Rails.application.eager_load!