子类上的急切加载关联
我有以下(简化的)类层次结构:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
Parent
模型中定义belongs_to :other
关联吗?它不会与每个Parent
对象相关,但这就是 STI 的本质:您几乎总会有一些某些列并不是每个子对象都使用。如果确实无法将关联移至父级,则可能需要分两步加载,例如:
Can you define the
belongs_to :other
association in theParent
model? It won't be relevant to everyParent
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:
由于
Child
继承自Parent
(而不是相反),因此Parent
不知道belongs_to :other
协会。我认为您需要重新考虑如何对应用程序进行建模。也许您的实际模型的一些细节会对您想要实现的目标的替代方法提出一些答案。
Since
Child
inherits fromParent
(and not the other way around),Parent
has no knowledge of thebelongs_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.