渴望在子类上加载关联

渴望在子类上加载关联

本文介绍了渴望在子类上加载关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下(简化的)类层次结构:

I have the following (simplified) class hierarchy:

def Parent < ActiveRecord::Base end
def Child < Parent
  belongs_to :other
end
def Other < ActiveRecord::Base end

我想获取所有Parent对象,如果它们是Child对象,则具有他们渴望加载:other关联。所以我希望我能做到:

I want to get all Parent objects and -if they are Child objects- have them eager load the :other association. So I had hoped I could do:

Parent.find(:all, :include => [:other])

但正如我担心的那样,我得到的信息是:找不到名为 other的协会;也许您拼写错误了吗?

But as I feared, I get the message: "Association named 'other' was not found; perhaps you misspelled it?"

在这种情况下建立紧急加载的最佳方法是什么?

What is the best way to establish eager loading in this scenario?


根据要求,下面是更具体的示例:

As requested, here's the more concrete example:


  • 父母=事件

  • 儿童= PostEvent

  • 其他= Post

我想记录不同类型的事件,所有事件它们自己的属性(其中一些是对其他对象的引用),例如上面的示例。同时,我希望能够列出所有发生的事件,因此列出父类。

I want to log different types of events, all with their own properties (some of which are references to other objects), like the above example. At the same time I want to be able to list all Events that occurred, hence the parent class.

推荐答案

您可以定义 Parent 模型中的 belongs_to:other 关联?它与每个 Parent 对象都不相关,但这就是STI的本质:您几乎总是拥有 some 列,而每个列都不使用

Can you define the belongs_to :other association in the Parent model? It won't be relevant to every Parent object, but that's the nature of STI: you will almost always have some column that's not used by every child.

如果您真的不能将关联移至父级,则可能需要分两个步骤进行加载,例如:

If you really can't move the association to the parent, you may have to load in two steps, for example:

Parent.find(:all, :conditions => "type != 'Child'") +
  Child.find(:all, :include => [:other])

这篇关于渴望在子类上加载关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:13