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 Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com
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? ThanksWell, 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)
There is however the issue that this won't find subclasses that
haven't been loaded yet.
Fred
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)
There is however the issue that this won't find subclasses that haven't been loaded yet.
Fred
Well, yes there is that. 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