开发者

How can I get model names from inside my app?

I have a bunch of models in a sub-directory that inherit from 开发者_如何学运维a model in the models root directory. I want to be able to set a class variable in another model that lists each inherited model class.

i.e

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

Not sure how to get at this info though...


There is a full answer here. Basically, you can either troll through the files or monkey-patch Class (or ActiveRecord). Those are two ways to go, at least.

Edit: On second thought, Rails won't load your Models until necessary, so while the "files" way seems weak, it's probably your only option (unless you want to do something in your models themselves).


In Rails, in production env this should work

Object.subclasses_of ClassInModelDir

You have to load the files manually If Rails.env.development?


You will not be able to do this unless you preload your descendant models. This is the reason why it is prudent to reengineer your code to use Class#ancestors instead of descendants (also descendants are not a core Ruby feature).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜