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:20

Assuming all models are in app/models and you have grep & awk on your server (majority of the cases),

# extract lines that match specific string, and print 2nd word of each line
results = `grep -r "< ActiveRecord::Base" app/models/ | awk '{print $2}'`
model_names = results.split("\n")

It it faster than Rails.application.eager_load! or looping through each file with Dir.

EDIT:

The disadvantage of this method is that it misses models that indirectly inherit from ActiveRecord (e.g. FictionalBook < Book). The surest way is Rails.application.eager_load!; ActiveRecord::Base.descendants.map(&:name), even though it's kinda slow.

查看更多
倾城一夜雪
3楼-- · 2019-01-02 17:21

I can't comment yet, but I think sj26 answer should be the top answer. Just a hint:

Rails.application.eager_load! unless Rails.configuration.cache_classes
ActiveRecord::Base.descendants
查看更多
永恒的永恒
4楼-- · 2019-01-02 17:22

This works for Rails 3.2.18

Rails.application.eager_load!

def all_models
  models = Dir["#{Rails.root}/app/models/**/*.rb"].map do |m|
    m.chomp('.rb').camelize.split("::").last
  end
end
查看更多
闭嘴吧你
5楼-- · 2019-01-02 17:23

This seems to work for me:

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

Rails only loads models when they are used, so the Dir.glob line "requires" all the files in the models directory.

Once you have the models in an array, you can do what you were thinking (e.g. in view code):

<% @models.each do |v| %>
  <li><%= h v.to_s %></li>
<% end %>
查看更多
梦该遗忘
6楼-- · 2019-01-02 17:23
def load_models_in_development
  if Rails.env == "development"
    load_models_for(Rails.root)
    Rails.application.railties.engines.each do |r|
      load_models_for(r.root)
    end
  end
end

def load_models_for(root)
  Dir.glob("#{root}/app/models/**/*.rb") do |model_path|
    begin
      require model_path
    rescue
      # ignore
    end
  end
end
查看更多
素衣白纱
7楼-- · 2019-01-02 17:24

The whole answer for Rails 3, 4 and 5 is:

If cache_classes is off (by default it's off in development, but on in production):

Rails.application.eager_load!

Then:

ActiveRecord::Base.descendants

This makes sure all models in your application, regardless of where they are, are loaded, and any gems you are using which provide models are also loaded.

This should also work on classes that inherit from ActiveRecord::Base, like ApplicationRecord in Rails 5, and return only that subtree of descendants:

ApplicationRecord.descendants

If you'd like to know more about how this is done, check out ActiveSupport::DescendantsTracker.

查看更多
登录 后发表回答