How do I get the model names from my application?

I have a bunch of models in a subdirectory that inherit from the model in the models root. I want to be able to set a class variable in another model that renders each inherited class of the model.

i.e

@@groups = sub_models.map do { |model| model.class.to_s }

      

Not sure how to get to this information though ...

+2


a source to share


3 answers


There is a complete answer here . Basically, you can either loop through files or a monkey patch class (or ActiveRecord). These are at least two paths.



Edit: Secondly, Rails won't load your Models until it's needed, so while the "files" path seems weak, this is probably your only option (unless you want to do something in your model).

0


a source


In Rails, in production env, this should work

Object.subclasses_of ClassInModelDir

      



You have to upload files manually. If Rails.env.development?

0


a source


You cannot do this unless you preload your descendant models. This is why it makes sense to reengineer your code to use Class#ancestors

instead descendants

(also descendants are not the main Ruby function).

0


a source







All Articles