Finding out what models exist in your application

Is there a way to reflect in Rails and find out what models are
defined in your application? Maybe generate an Array with model names?
Thanks

On Jun 16, 2008, at 12:34 PM, saljamil wrote:

Is there a way to reflect in Rails and find out what models are
defined in your application? Maybe generate an Array with model names?
Thanks

Well, you can look at the files in app/models/, but I suspect that’s
not what you want to hear.

If you mean specifically the models that are based on ActiveRecord,
then you can do:

ActiveRecord::Base.send(:subclasses)

It’s peeking under the covers a bit because it is a private method
(hence the use of send). If you have STI models, only the top-most
one is a direct subclass of ActiveRecord::Base so you have to deal
with that if it is any issue for you.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

On 16 Jun 2008, at 17:46, Rob B. wrote:

If you mean specifically the models that are based on ActiveRecord,
then you can do:

ActiveRecord::Base.send(:subclasses)

There is however the issue that this won’t find subclasses that
haven’t been loaded yet.

Fred

On Jun 16, 2008, at 12:47 PM, Frederick C. wrote:

If you mean specifically the models that are based on ActiveRecord,
then you can do:

ActiveRecord::Base.send(:subclasses)

There is however the issue that this won’t find subclasses that
haven’t been loaded yet.

Fred

Well, yes there is that. :wink: In the code I have that uses this,
there’s first:

 for f in Dir.glob(File.join(RAILS_ROOT || '.', "app/models",

“*.rb”))
puts “getting #{f}…” if options.debug
require f
end

So I avoid that particular problem.

Perhaps if the OP tells us what is really needed…

ActiveRecord::Base.connection.tables.reject{|t|t=~/schema/}.map do |
t|
t.singularize.camelize.constantize
end

-Rob