子类上的急切加载关联

发布于 2024-08-19 05:36:49 字数 579 浏览 4 评论 0原文

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

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

我想获取所有父对象,并且 - 如果它们是子对象 - 让它们急切加载 :other 关联。所以我希望我能做到:

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

但正如我担心的那样,我收到消息:“未找到名为‘other’的关联;也许您拼写错误?”

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

[编辑] 根据要求,这里是更具体的示例:

  • Parent = Event
  • Child = PostEvent
  • Other = Post

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

I have the following (simplified) class hierarchy:

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

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])

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?

[Edit]
As requested, here's the more concrete example:

  • Parent = Event
  • Child = PostEvent
  • Other = 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

打小就很酷 2024-08-26 05:36:49

您可以在 Parent 模型中定义 belongs_to :other 关联吗?它不会与每个 Parent 对象相关,但这就是 STI 的本质:您几乎总会有一些某些列并不是每个子对象都使用。

如果确实无法将关联移至父级,则可能需要分两步加载,例如:

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

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])
青瓷清茶倾城歌 2024-08-26 05:36:49

由于 Child 继承自 Parent(而不是相反),因此 Parent 不知道 belongs_to :other 协会。

我认为您需要重新考虑如何对应用程序进行建模。也许您的实际模型的一些细节会对您想要实现的目标的替代方法提出一些答案。

Since Child inherits from Parent (and not the other way around), Parent has no knowledge of the belongs_to :other association.

I think you need to reconsider how you're modeling your app. Perhaps some specifics on your actual models would raise some answers on alternative methods of what you're trying to accomplish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文