views:

207

answers:

2

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  A: 

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.

bensie
+1  A: 

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])
Alex Reisner
this second line won't work because it's essentially the same as the code in the question
neutrino
Yikes, you're right--typing without thinking. It's fixed now. Thanks.
Alex Reisner
Hmmm... both options are kind of smelly in that you feel like there has to be some better way. But it is indeed a valid workaround.
Pascal Lindelauf
Yeah, I don't think there's a cleaner way to get this working based on the code you've given. However, given that you're already willing to accept the messiness of unused columns in an STI setup, putting the association in `Parent` isn't really any different. In fact it's cleaner in a sense because `Parent` has a useless `other_id` attribute anyway. To prevent problems, you could add validation that requires `other_id` to be `nil` unless the object is a `Child`.
Alex Reisner