eager loading association on a subclass

2019-02-26 09:42发布

问题:

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.