1

我目前对使用descendantsActiveRecord::Base-Objects 感到非常困惑。我浏览了互联网并测试了所有解决方案,但没有一个适合我的需求。

我想要做什么:获取所有 ActiveRecord::Base 子类的数组,包括这些子类的子类,例如

Entity < ActiveRecord::Base
ChildEntity < Entity

Property < ActiveRecord::Base

我当前的问题:ActiveRecord::Base.descendants 没有列出从 ActiveRecord::Base 继承的所有类。也许错在我这边:这是我的代码。

 def all_entities
   rec_all_entities(ActiveRecord::Base)
 end

 def rec_all_entities(motherEntity)
    logger.debug("mother: " + motherEntity.to_s + " descendants: " + motherEntity.descendants.to_s)
    motherEntity.descendants.each do |childEntity|
      rec_all_entities(childEntity)
    end
 end  

出于调试目的,我只是打印出来。我正在使用 Rails 3。

我认为错误必须出在我的代码中。我正在调用当前视图中的方法<% all_entities %>

谢谢你的帮助。

4

2 回答 2

7

这对我来说效果很好。另外,取自Is there a way to get a collection of all the Models in your Ra​​ils app?

> Rails.application.eager_load!
> ActiveRecord::Base.descendants
于 2014-01-04T02:17:32.350 回答
1

如果您处于开发模式,则必须先触摸每个模型,然后它才会被拾取desendants

取自Is there a way to get a collection of all the Models in your Ra​​ils app?

于 2012-02-17T22:45:49.623 回答