是否有一种方法可以获得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读取或扩展Class类……

ActiveRecord::Base.send :subclasses

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

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

如果你只需要类名:

ActiveRecord::Base.descendants.map {|f| puts f}

只需在Rails控制台中运行它,仅此而已。好运!

编辑:@sj26是正确的,你需要在调用后代之前先运行这个:

Rails.application.eager_load!

如果有人觉得这个例子有用,我就随便举个例子。解决方案是基于这个答案https://stackoverflow.com/a/10712838/473040。

假设您有一个列public_uid,它被用作外部世界的主ID(您可以在这里找到为什么要这样做的原因)

现在假设您已经在一些现有的model上引入了这个字段,现在您想要重新生成所有尚未设置的记录。你可以这样做

# lib/tasks/data_integirity.rake
namespace :di do
  namespace :public_uids do
    desc "Data Integrity: genereate public_uid for any model record that doesn't have value of public_uid"
    task generate: :environment do
      Rails.application.eager_load!
      ActiveRecord::Base
        .descendants
        .select {|f| f.attribute_names.include?("public_uid") }
        .each do |m| 
          m.where(public_uid: nil).each { |mi| puts "Generating public_uid for #{m}#id #{mi.id}"; mi.generate_public_uid; mi.save }
      end 
    end 
  end 
end

现在可以运行rake di:public_uid:generate

一行:Dir['app/models/\*.rb']。map {|f|文件。basename .camelize (f,“。*”)。constantize}

这似乎对我很管用:

  Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require file }
  @models = Object.subclasses_of(ActiveRecord::Base)

Rails只在使用模型时加载模型,因此Dir。Glob行“需要”models目录中的所有文件。

一旦你在数组中有了模型,你可以做你想做的事情(例如在视图代码中):

<% @models.each do |v| %>
  <li><%= h v.to_s %></li>
<% end %>