How can I iterate through all of the Models in my rails app?

后端 未结 5 2144
天命终不由人
天命终不由人 2021-02-08 17:51

I would like to be able to iterate over and inspect all the models in my rails app. In pseudo-code it would look something like:

rails_env.models.each do |model|         


        
5条回答
  •  长情又很酷
    2021-02-08 18:07

    Similar to nathanvda's response, use camelize rather than capitalize to support model files with underscores, and use String#constantize rather than Kernel.const_get.

    Additionally, if you keep non-activerecord models in your models folder (e.g. a search class for consolidating search logic), you'll want to check the class is an active record model.

    Dir[Rails.root.join('app/models/*.rb').to_s].each do |filename|
      klass = File.basename(filename, '.rb').camelize.constantize
      next unless klass.ancestors.include?(ActiveRecord::Base)
      next if klass.abstract_class?
      # do something with klass
    end
    

提交回复
热议问题