开发者

eager loading association on a subclass

开发者 https://www.devze.com 2022-12-18 11:01 出处:网络
I have the following (simplified) class hierarchy: def Parent < ActiveRecord::Base end def Child < Parent

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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号