eager loading association on a subclass

旧街凉风 提交于 2019-12-02 07:27:19

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2149850/eager-loading-association-on-a-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!