是否有一种方法可以获得Rails应用程序中所有模型的集合?

基本上,我能做的是:-

Models.each do |model|
  puts model.class.name
end

当前回答

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

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

其他回答

Rails 3、4和5的完整答案是:

如果cache_classes是关闭的(在开发中默认是关闭的,但在生产中是打开的):

Rails.application.eager_load!

然后:

ActiveRecord::Base.descendants

这将确保加载应用程序中的所有模型,无论它们位于何处,并且也加载了您使用的任何提供模型的gem。

这应该也适用于从ActiveRecord::Base继承的类,如Rails 5中的ApplicationRecord,并只返回后代的子树:

ApplicationRecord.descendants

如果您想了解更多关于这是如何完成的,请查看ActiveSupport:: descent stracker。

刚刚看到这个,因为我需要打印所有模型的属性(基于@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}"}}

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

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

如果你只需要类名:

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

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

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

Rails.application.eager_load!

是的,有很多方法可以找到所有的模型名称,但我在我的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