Preloading children of child rows


#1

I am working on a rails app to serve as the admin app for an existing
java webapp. For this reason, I am constrained by the current database
structure, which does not by any means conform to the ideal rails
defaults.

Anyway, I have the following models:

class Provider…
belongs_to: login

class Login…
has_and_belongs_to_many :demographics

class Demograpics…

Everyone has a login. Everyone has one demographic row (why is it habtm
you ask? just bad database design). But not all logins are
providers–there are other kinds of users.

What I want to do is create a query with find() that will preload all
login and demographic information associated with providers.

If I do this:
Provider.find(:all, :include => [:login])

That includes the login stuff but does not preload the login.demographic
rows.

Actually, what I want is not only to include the demographic rows but to
use columns in them as conditions to the query. For example, the
following syntax will not work, but it indicates what I want to do:

Provider.find(:all, :include => [:login, :login.demographic]
:conditions => ‘(demographic.foo is null or demographic.bar is null)’)

Now I am using find_by_sql but I feel like there has to be a Rails Way
to do this…Can anyone point it out?
Thanks