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

其他回答

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

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

或更短:

ApplicationRecord.descendants.collect(&:name)

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

Rails.application.eager_load!

我寻找了很多方法,最后选择了这种方式:

in the controller:
    @data_tables = ActiveRecord::Base.connection.tables

in the view:
  <% @data_tables.each do |dt|  %>
  <br>
  <%= dt %>
  <% end %>
  <br>

来源:http://portfo.li/rails/348561-how-can-one-list-all-database-tables-from-one-project

我认为@hnovick的解决方案是一个很酷的,如果你没有表的模型。这个解决方案也可以在开发模式下工作

但我的方法略有不同

ActiveRecord::Base.connection.tables.map{|x|x.classify.safe_constantize}.compact

分类应该能从字符串中正确地给出类名。safe_constantise确保您可以安全地将其转换为类,而不会抛出异常。如果您的数据库表不是模型,则需要这样做。紧凑,以便删除枚举中的任何nil。

可以检查一下

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

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