Using :include "recursively" (including the children of the

Hi,

Let’s say I have the following hierarchy of tables:

Group <- parent
Location <- child of Group
School <- child of Location
Phone <- child of School

Then, if I want to do this:

Location.find(…someparms…, :include => [:schools, :group, :phones])

I get an association error (Association was not found). I guess it
happens because AR is looking in the Location model for the Phones
association, which only exists in the School model (I also tried
singular, :phone).

Is there any way I can load all Phone records at once? I wouldn’t mind
using custom SQL if that’s the only solution.

Thanks in advance!

Ivan V.

PS: Merrrrry christmas!

On Fri, Dec 16, 2005 at 02:14:57PM -0600, Iv?n Vega R. wrote:

Is there any way I can load all Phone records at once? I wouldn’t mind
using custom SQL if that’s the only solution.

There is no way to do that using the eager loading implementation. It
would
require custom SQL.

marcel

Marcel Molina Jr. wrote:

Would it be possible to load the phones for the object:

@locs = Location.find(…someparms…, :include => [:schools, :group])

and then something like:

@locs.schools.phones.load_all (of course this method doesn’t exist, but
is there something similar?)

Or could I “find” all the phones that belong to certain schools and then
assign those to the specific @locs.schools object?

Thanks!

Ivan V.

If it’s just for the location, then you could include a redundant
foreign
key (has_many) to the phones. Then you could use Location.find(
…someparams :include => [:phones])

Alternativley a method in the Locations model could look something like
for
the current location

def self.get_phones
Phone.find_by_sql(
“SELECT phones.* FROM phones p, locations l, schools s
WHERE l.id = #{id} AND s.location_id = l.id AND p.school_id =
s.id”)
end

In which case you could use @some_location.get_phones

going a bit further than that it might be possible to use something like

@phone_numbers = Location.find( :all ).collect { |loc|
loc.get_phones}
@phone_numbers.flatten!

I haven’t tested andy of this tho… Hope it works :slight_smile: