get a list of all models from rails

<>

This question already has an answer here:

Answers


Since Rails doesn't load classes unless it needs them, you must read the models from the folder. Here is the code

Dir.glob(Rails.root + '/app/models/*.rb').each { |file| require file }
  @models = Object.subclasses_of(ActiveRecord::Base).select { |model| 
   model.name[-4..-1] == "Cube"
  } 

in rails 3 you'd swap @models for:

@models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort

For Rails 3

@models = ActiveRecord::Base.
    descendants.
    select{|x| x.name[-4..-1] == "Cube"}

@models = ActiveRecord::Base.descendants.map(&:name)

gives you all the model names which either inherit form ActiveRecord::Base or is a subclass of any existing model.


I was googling answer how to show all Ralis models, combination of answers here was weary helpful, thx.

so here is combination of solutions that works even for STI tables on Rails

#Since Rails doesn't load classes unless it needs them, you must read the models from the folder. Here is the code
Dir[Rails.root.to_s + '/app/models/**/*.rb'].each do |file| 
  begin
    require file
  rescue
  end
end

models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort

models.each do |model|
  print model
  print '  '
end

Need Your Help

Iterating through a vector of pointers

c++ pointers object vector

I'm trying to iterate through a Players hand of cards.

Hide page until everything is loaded Advanced

javascript jquery document-ready

I have a webpage which heavily makes use of jQuery.