【问题标题】:List all Models in inheritance tree beginning from ActiveRecord::Base列出继承树中从 ActiveRecord::Base 开始的所有模型
【发布时间】:2011-07-17 17:38:16
【问题描述】:

我目前对将descendants 用于 ActiveRecord::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。

我认为问题一定出在我的代码上。我正在使用&lt;% all_entities %&gt;调用当前视图中的方法

感谢您的帮助。

【问题讨论】:

标签: ruby-on-rails-3 list inheritance models descendant


【解决方案1】:

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

> Rails.application.eager_load!
> ActiveRecord::Base.descendants

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多