Is there a way to get a collection of all the Mode

2019-01-02 16:30发布

Is there a way that you can get a collection of all of the Models in your Rails app?

Basically, can I do the likes of: -

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

27条回答
低头抚发
2楼-- · 2019-01-02 17:24

In just one line:

 ActiveRecord::Base.subclasses.map(&:name)
查看更多
一个人的天荒地老
3楼-- · 2019-01-02 17:24
Module.constants.select { |c| (eval c).is_a?(Class) && (eval c) < ActiveRecord::Base }
查看更多
妖精总统
4楼-- · 2019-01-02 17:25

I've tried so many of these answers unsuccessfully in Rails 4 (wow they changed a thing or two for god sakes) I decided to add my own. The ones that called ActiveRecord::Base.connection and pulled the table names worked but didn't get the result I wanted because I've hidden some models (in a folder inside of app/models/) that I didn't want to delete:

def list_models
  Dir.glob("#{Rails.root}/app/models/*.rb").map{|x| x.split("/").last.split(".").first.camelize}
end

I put that in an initializer and can call it from anywhere. Prevents unnecessary mouse-usage.

查看更多
登录 后发表回答