views:

61

answers:

1

The newer style of eager loading uses multiple queries to load associations. Is it possible to add conditions to those additional eager loading queries? e.g.

Bakery.find(:all, :include => :bakers)

will generate an eager loading query similar to this:

SELECT bakers.* FROM bakers WHERE (bakers.bakery_id IN (1,2,3,4,5))

Is it possible to add conditions to this eager loading query?

Update: To (maybe) make this clearer, the query I am wanting to replicate with AR (sans SQL) is:

SELECT * FROM bakeries LEFT JOIN bakers ON bakeries.id=bakers.bakery_id AND bakers.hat = 'on'

Specifically, I was hoping to be able to modify the second eager loaded SQL statement to be:

SELECT bakers.* FROM bakers WHERE (bakers.bakery_id IN (1,2,3,4,5) AND bakers.hat = 'on')

Is this possible, or must I use SQL? Just looking for the "Rails" way to do it. :)

+1  A: 

Well, what in particular are you wanting to change in the associated query?

You can certainly do somethinglike this:

Bakery.find(:all, :include => :bakers, :conditions => ["bakers.something = ?", true])

If we had a little more info, there may be a better way to do it. Depending on what you're looking for, you may want to look into named_scopes, which you can chain together, like:

Bakery.bakers.available

named_scope is pretty neat.

Bill Turner
Thanks for the reply Bill. I've tried this, but it performs a join, returning only bakeries with bakers matching the conditions provided. What I would like, is to get all the bakeries, with only specific bakers loaded eagerly. Basically, an eager loaded equivalent of these two queries: bakeries = Bakery.find(:all); bakers = bakeries.find(:all, :conditions => { :hat => 'on' })
Jay
To add more, I'm currently using Bakery.find(:all), and in my view, for each bakery, am using: bakery.bakers.find(:all, :conditions => { :hat => 'on' }). Looking for a way to do this, but without all the additional queries.
Jay
Thanks for the clarifications. I'm not totally sure if there's a way to get exactly what you need. Maybe play with a couple of named_scopes and see if that does what you need, but I have a feeling it won't either.
Bill Turner
After much reading, I've come to the same conclusion. Which is strange, because it seems trivial. Just figured I was overlooking something. Which, I still hope I am. Thanks Bill!
Jay